Store and retrieve file with SQL Server

Hello every one,
here i am describing how to read and store text file using SQL server.


// Store file in SQL Server

FileStream objFileStream = new FileStream("[Path of File]", FileMode.Open);
byte[] Data = new byte[objFileStream.Length];
objFileStream.Read(Data, 0, Convert.ToInt32(objFileStream.Length));

SqlConnection objConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["My"].ToString());
objConnection.Open();
SqlCommand objCommand = new SqlCommand("Bytes_Insert");
objCommand.Connection = objConnection;
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.Parameters.Add(new SqlParameter("@Data", Data));
objCommand.ExecuteNonQuery();
objConnection.Close();
objFileStream.Close();

// Retrieve file from SQL Server

SqlConnection objConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["My"].ToString());
objConnection.Open();
SqlCommand objCommand = new SqlCommand("Bytes_ListAll");
objCommand.Connection = objConnection;
objCommand.CommandType = CommandType.StoredProcedure;

SqlDataAdapter adpt = new SqlDataAdapter(objCommand);
DataSet ds = new DataSet();
adpt.Fill(ds);

byte[] Data = (byte[]) ds.Tables[0].Rows[0]["Data"];
File.WriteAllBytes("[Path to store File]", Data);


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: