How to store word documents as BLOB in Database using C#

We can store word documents in Database as a BLOB (Binary Large OBject).. We need to convert the document into binary format using BinaryReader class before it gets passed to Database. Following code block shows how to convert and store a word document in Database.

// file path to read file
string filePath = @"D:\test.txt"; 

// declare and initialize FileStream object
FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

// declare and initialize BinaryReader object
BinaryReader reader = new BinaryReader(stream);

// Read bytes  from the file
byte[] file = reader.ReadBytes((int)stream.Length);

// always Remember  to close the handles, 
// or resources remain locked
reader.Close();
stream.Close()

Following code block shows how to write bytes to database.


// connection string
string connectionString = "";

// declare and initialize SqlConnection object
SqlConnection connection = new SqlConnection(connectionString);

// declare and initialize SqlCommand object.
// Remember File column is  Blob in database
SqlCommand  command =
 new SqlCommand("INSERT INTO FileTable (File) Values(@File)", connection);

// add parameters to SqlCommand  object
command.Parameters.Add("@File", SqlDbType.Binary, file.Length).Value = file;

// open connection
connection.Open();

// execute command
command.ExecuteNonQuery();