SoFunction
Updated on 2025-03-08

C# How to store images in SQL SERVER database

This article describes the method of storing images in SQL SERVER database in C#. Share it for your reference. The details are as follows:

Step 1:

//Get the currently selected imagethis. = (this.());
//Get the path to the current imagestring path = ();
//Add the path image to the FileStream classFileStream fs = new FileStream(path, , );
//Instantiate the BinaryReader object through the FileStream objectBinaryReader br = new BinaryReader(fs);
//Convert FileStream class object into binary array through the ReadBytes() method of BinaryReader class objectbyte[] imgBytesIn = (Convert.ToInt32());

Step 2:

//Add pictures to the databasestring sql="insert into pic values(@pic)"; 
SqlParameter[] param = new SqlParameter[] { new SqlParameter("@pic", imgBytesIn) };
(sql, param);

Step 3:

//Fetch the image from the databasestring sql="select * from pic where id=0";
SqlDataReader reader = (sql, null);
MemoryStream mss = null;
if (())
{
  byte[] bytes = (byte[])reader["pic"];
  mss = new MemoryStream(bytes);
}
this. = (mss);

I hope this article will be helpful to everyone's C# programming.