This blog is moved to
http://amalhashim.wordpress.com

Thursday, February 19, 2009

Store/Retrieve file from Database

// 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);

No comments: