0

hi,

I am working in C# windows application as front end and sql server 05 as back end.

I want retrieve image from database. Image,imagenm, image path save in the database.

The code given below shows an error message i.e
Unable to cast object of type 'System.String' to type 'System.Byte[]'. on this line : byte[] Img = (byte[])cmd.ExecuteScalar();

SqlConnection con = new SqlConnection(s);
            SqlCommand cmd = new SqlCommand();
            try
            {
                con.Open();
                cmd.Connection = con;
                cmd.CommandText = "select FullPath,MyImageSample from tblImages where nm=" + txt_nm.Text.ToString();
                
   [B] byte[] Img = (byte[])cmd.ExecuteScalar();[/B]
                   string str = Convert.ToString(DateTime.Now.ToFileTime());
                  
                    FileStream fs = new FileStream(str, FileMode.CreateNew, FileAccess.Write);
                    fs.Write(Img, 0, Img.Length);
                    fs.Flush();
                    fs.Close();
                    pic1.Image = Image.FromFile(str);


            }
            catch
            {
                MessageBox.Show("Error while saving image.", "Error");
            }
            finally
            {
                con.Close();
            }

can u please help me to solve this.

2
Contributors
1
Reply
4
Views
5 Years
Discussion Span
Last Post by Mitja Bonca
1

simpliest way to convert stirng to byte[] is:

string str = "some text";
byte[] byteArr = Encoding.UTF8.GetBytes(str);

in your case it seems that you dont have type of byte in the database, but its varchar, so you can only read it to string, like:

string str = (string)cmd.ExecuteScalar();

Edited by Mitja Bonca: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.