Wednesday, March 19, 2008

How to convert String to Byte and upload to SQL DB column having datatype as Image..

string strImageName=string.Empty;
strImageName="Hi, This is Test String";
//Assigning string as Byte
byte[] byImageName=(new ASCIIEncoding()).GetBytes(strImageName.ToString());

//uploading to database column as Image Type
SqlCommand cmd=new SqlCommand();
cmd.Connection=conn;
cmd.CommandText ="update table1 set imagecol=@imagecol where id='123'";
cmd.Parameters.Add (new SqlParameter("@imagecol",SqlDbType.Image) ).Value=
(new ASCIIEncoding()).GetBytes(strImageName.ToString());
int result=cmd.ExecuteNonQuery();
Response.Write("Affected Rows: " + res);
cmd.Dispose();

Note: SQL Datatype "Image" and few others are getting obselete / repalced in latter versions...Microsoft Recommends not to use these datatypes in your development going further.
Hope this helps someone....

No comments: