OpenFileDialog OpenFileDialog1 =NewOpenFileDialog (); if(OpenFileDialog1. ShowDialog () = =DialogResult.OK) {TextBox1.Text= OpenFileDialog1. FileName;//file path } stringImageName = DateTime.Now.ToString ("YYYYMMDDHHMMSS");//generate file name to databaseFileStream FS=NewFileStream (TextBox1.Text, FileMode.Open); BinaryReader BR=NewBinaryReader (FS); Byte[] Bydata= Br. Readbytes ((int) fs. Length);//generating a binary streamFS. Close (); //Convert a picture into a binary stream and store it in a database stringconn ="server=.; Database=imagedb; Uid=sa; pwd=1234"; SqlConnection myconn=NewSqlConnection (conn); MyConn. Open (); stringstr ="INSERT INTO ImageFile (Imagename,imagecontext) VALUES (@name, @file)"; SqlCommand Mycomm=NewSqlCommand (str, myconn); Mycomm. Parameters.Add ("@file", Sqldbtype.binary, bydata.length); Mycomm. parameters["@file"]. Value =Bydata; Mycomm. Parameters.Add ("@name", SqlDbType.NVarChar, -); Mycomm. parameters["@name"]. Value =ImageName; Mycomm. ExecuteNonQuery ();//writes a binary stream to the database, corresponding to the database image typemyconn. Close (); //turn binary into imagestr ="Select top 1 imagecontext from ImageFile where Imagename= '"+ ImageName +"'"; MyConn=NewSqlConnection (conn); SqlDataAdapter SDA=NewSqlDataAdapter (STR, conn); DataSet myds=NewDataSet (); MyConn. Open (); Sda. Fill (myds); MyConn. Close (); Byte[] Files= (byte[]) myds. tables[0]. rows[0]["Imagecontext"]; MemoryStream Ms=NewMemoryStream (Files); Image I=Image.fromstream (MS); pictureBox1.Image= i;//bind to the PictureBox1 control
C # pictures stored in SQL Server database