Sunday, February 8, 2009

Saving an image into SQL server database in C# Windows Application.

//Reading image in to File Stream from a Physical Location
FileStream fs = new FileStream(@"C:\image1.jpg", FileMode.Open, FileAccess.Read);
Initialize a binary reader to read Binary data from image
BinaryReader br = new BinaryReader(fs);

//Next use the ReadByte(or any other equivalent ) method to read image data in to byte array
byte[] photo = br.ReadBytes((int)fs.Length);

//Close the binary reader AND filestream object
br.Close();
fs.Close();

//Next Create a SQL command which makes use of SQL parameters
SqlCommand addEmp = new SqlCommand("INSERT INTO Employees
("+FirstName,Photo) " + "VALUES(@FirstName,@Photo)",conn);
addEmp.Parameters.Add("@FirstName", SqlDbType.NVarChar, 10).Value = pfirstName;

//Assign the byte array to the corresponding SQL parameter
addEmp.Parameters.Add("@Photo", SqlDbType.Image, photo.Length).Value = photo;
conn.Open();

//Execute the query and Finaly You are Done
addEmp.ExecuteNonQuery();
conn.Close();

//Enjoy!

1 comment:

LinkWithin

Related Posts with Thumbnails