Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
please give the code for upload and save picture through picturebox in c#..
this is the code for upload which i made but exception handling error comes please help me out..
C#
private void btnupload_Click(object sender, EventArgs e)
    {
      try
      {
        openFileDialog1.ShowDialog(this);
        openFileDialog1.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
        
        byte[] image;
 
        string fileName =openFileDialog1.FileName;
 
        FileStream fs = new FileStream(fileName, FileMode.Open);
        BinaryReader reader = new BinaryReader(fs);
        image = reader.ReadBytes((int)fs.Length);
        fs.Close();
 
        SqlConnection conn = new SqlConnection("connectionString");
        conn.Open();
        string query = "Insert into pictures (name,images) values(@name,@images)";
 
        SqlCommand comm = new SqlCommand(query, conn);
        comm.Parameters.AddWithValue("name", Path.GetFileName(strFn).ToString());
 
        comm.Parameters.AddWithValue("images", image);
 
        comm.ExecuteNonQuery();
        MessageBox.Show("Record Added");
 
        conn.Close();
        bind();
        pictureBox1.Image = new Bitmap(strFn);
      
      }
      catch (Exception)
      {
        throw new ApplicationException("Failed loading image");
      }     
    }



thanks
Posted
Updated 24-Jun-11 0:00am
v2
Comments
Slacker007 24-Jun-11 6:00am    
Edited: added the obligatory code block.

Your sending

  comm.Parameters.AddWithValue("name", Path.GetFileName(strFn).ToString());

You should send string fileName; 
 
Share this answer
 
Try
byte[] ReadFile(string sPath)
       {
           //Initialize byte array with a null value initially.
           byte[] data = null;
           //Use FileInfo object to get file size.
           FileInfo fInfo = new FileInfo(sPath);
           long numBytes = fInfo.Length;
           //Open FileStream to read file
           FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
           //Use BinaryReader to read file stream into byte array.
           BinaryReader br = new BinaryReader(fStream);
           //When you use BinaryReader, you need to supply number of bytes to read from file.
           //In this case we want to read entire file. So supplying total number of bytes.
           data = br.ReadBytes((int)numBytes);
           return data;
       }


at click event of buttonupload try
byte[] imageData = ReadFile(openFileDialog1.FileName);

and pass these imagedata value to sqlcommand parameter as
comm.Parameters.AddWithValue("images",(object)imageData);
 
Share this answer
 

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