Click here to Skip to main content
15,886,661 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
i am trying to Upload an image into sqlserver2008 using Winforms(C#)

C#
// sourcecode

string strFileFullPath="this is my image location";

in Database i took Varbinary(max) as DataType

FileStream stream = new FileStream(strFileFullPath, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(stream);

byte[] photo = reader.ReadBytes((int)stream.Length);

C#
// sourcecode
Error : Failed to convert parameter value from a String to a Byte[].

can you please help me how can i solve this issue

Thanks in advance
Posted
v3

1 solution

Hello try this code. If you find any easy solution than of mine then please reply me. Thanks...

C#
private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.png;*.jpg";
            if (open.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = open.FileName;
            }
            cn.Open();
            string image = textBox1.Text;
            Bitmap bmp = new Bitmap(image);
            FileStream fs = new FileStream(image, FileMode.Open, FileAccess.Read);
            byte[] bimage = new byte[fs.Length];
            fs.Read(bimage, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            SqlCommand cmd = new SqlCommand("insert into ImageUpload(imgdata) values(@imgdata)",cn);
            cmd.Parameters.AddWithValue("@imgdata",SqlDbType.Image).Value=bimage;
            cmd.ExecuteNonQuery();
            cn.Close();
        }
 
Share this answer
 
v2
Comments
Balu Balaji 23-Apr-13 3:37am    
it's fine but i am getting error like
Index was outside the bounds of the array.
i am trying to save 4kb image into varbinary(max) in sqlserver2008 is it problem? is it required to compress? if yes then how can i?
Chiklu.Soumya 23-Apr-13 3:45am    
Hello... I have used this code with Image datatype in Sql server 2008,2012. Varbinary was working only in Sql 2005. Don't think it's problem using varbinary. Now i"ll try and will respond u if i succeed.
Chiklu.Soumya 23-Apr-13 3:48am    
Yeah...It's working. In my code change SqlDbType.Image to SqlDbType.VarBinary. It's working. By the way Thanks for your question.
Balu Balaji 23-Apr-13 4:14am    
Thank you soo may be in passing parameters it's a problem i think

once again thank you dude......
Chiklu.Soumya 23-Apr-13 4:20am    
Welcome..........

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900