September 15, 2015

How to upload image to database in C#.net Windows Application

To Upload

    SqlConnection cn= new SqlConnection(connectionString);
    OpenFileDialog open = new OpenFileDialog();
    open.Filter = "Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.png;*.jpg";
    if (open.ShowDialog() == DialogResult.OK)
    {
        textBoximage.Text = open.FileName;
    }

    cn.Open();
    string image = textBoximage.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 TableName(imgdata) values(@imgdata)",cn);
    cmd.Parameters.AddWithValue("@imgdata",SqlDbType.Image).Value=bimage;
    cmd.ExecuteNonQuery();
    cn.Close();
}


To Retrieve

cn.Open();
 SqlDataAdapter da = new SqlDataAdapter(new SqlCommand("Select Picture From TableName where FieldName=condition ", cn));
 DataSet ds = new DataSet();
 da.Fill(ds);
 byte[] myImage = new byte[0];
 myImage = (byte[])ds.Tables[0].Rows[0]["Picture"];
 MemoryStream stream = new MemoryStream(myImage);
 pictureBox1.Image = Image.FromStream(stream);
 cn.Close();

No comments:

Post a Comment