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.

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();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.