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();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s