Blue Theme Orange Theme Green Theme Red Theme
 
ASP.NET Web Hosting – Click Here
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
New MS SQL 2008 Available - DiscountASP.NET
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ADO.NET & Database » Working with binary large objects (BLOBs)

Working with binary large objects (BLOBs)

This article illustrates how to work with binary large objects (BLOBs), it will show you how to save and retrieve BLOB values in a database.

Technologies: .NET 1.0/1.1, ADO.NET,Visual C# .NET
Total downloads : 388
Total page views :  13453
Rating :
 5/5
This article has been rated :  4 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
WorkingWithBLOBs.zip
 
ArticleAd
Become a Sponsor



Introduction:

You can define a BLOB as a large photo, document, audio etc. saved in binary formats that you want to save in a database.
Saving and retrieving BLOBs in a database is more complex than querying string or numeric data.

The BLOB may be very large and if you try to move it in one piece will consume a lot of system memory and that for sure will affect your application performance.

To reduce the amount of system memory you have to break up the BLOB into smaller pieces.

There are a lot of classes that are designed for moving large amount of binary data like BinaryRader, BinaryWriter which exists in System.IO namespace. In the next paragraphs you will see how to use all of this.

Saving a BLOB value to the database:
 
To save a BLOB value to database we use FileStream and BinaryReader classes.

The next example will show you the process of saving a BLOB to a database.

string filePath = @"D:\\My Movie.wmv";

 

//A stream of bytes that represnts the binary file

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

 

//The reader reads the binary data from the file stream

BinaryReader reader = new BinaryReader(fs);

 

//Bytes from the binary reader stored in BlobValue array

byte[] BlobValue = reader.ReadBytes((int)fs.Length);

 

fs.Close();

reader.Close();

 

SqlConnection BlobsDatabaseConn = new SqlConnection("Data Source = .; Initial Catalog = BlobsDatabase; Integrated Security = SSPI");
SqlCommand SaveBlobeCommand = new SqlCommand();

SaveBlobeCommand.Connection = BlobsDatabaseConn;

SaveBlobeCommand.CommandType = CommandType.Text;

SaveBlobeCommand.CommandText = "INSERT INTO BlobsTable(BlobFileName, BlobFile)" + "VALUES (@BlobFileName, @BlobFile)";

SqlParameter BlobFileNameParam = new SqlParameter("@BlobFileName", SqlDbType.NChar);

SqlParameter BlobFileParam = new SqlParameter("@BlobFile", SqlDbType.Binary);

SaveBlobeCommand.Parameters.Add(BlobFileNameParam);

SaveBlobeCommand.Parameters.Add(BlobFileParam);

BlobFileNameParam.Value = filePath.Substring(filePath.LastIndexOf("\\") + 1);

BlobFileParam.Value = BlobValue;

try

{

    SaveBlobeCommand.Connection.Open();

    SaveBlobeCommand.ExecuteNonQuery();

    MessageBox.Show(BlobFileNameParam.Value.ToString() + " saved to database.","BLOB Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);

}

catch(Exception ex)

{

    MessageBox.Show(ex.Message, "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);

}

finally

{

    SaveBlobeCommand.Connection.Close();

}

Retrieving a BLOB from the database:

To retrieve a BLOB value from database we use FileStream and BinaryWriter classes.

The next example will show you the process of retrieving a BLOB to a database.

NOTE: you will see that we set the CommandBehavior to SquentialAccess when we call ExecuteReader() method, this allow us to use the GetBytes() method of the SqlDataRader, so we can read the BLOB from database in smaller, user-definable amounts.

string
SavePath = @"D:\\My BLOBs";

SqlConnection SaveConn = new SqlConnection("Data Source = .; Initial Catalog = BlobsDatabase; Integrated Security = SSPI");

SqlCommand SaveCommand = new SqlCommand();

SaveCommand.CommandText = "Select BlobFileName, BlobFile from BlobsTable where BlobFileName = @BlobFileName";

SaveCommand.Connection = SaveConn;

SaveCommand.Parameters.Add("@BlobFileName", SqlDbType.NVarChar).Value = "My Movie.wmv";


//the index number to write bytes to

long CurrentIndex = 0;


//the number of bytes to store in the array

int BufferSize = 100;


//The Number of bytes returned from GetBytes() method

long BytesReturned;


//A byte array to hold the buffer

byte[] Blob = new byte[BufferSize];


SaveCommand.Connection.Open();


//We set the CommandBehavior to SequentialAccess

//so we can use the SqlDataReader.GerBytes() method.


SqlDataReader
reader = SaveCommand.ExecuteReader(CommandBehavior.SequentialAccess);


while
(reader.Read())

{

    FileStream fs = new FileStream(SavePath + "\\" + reader["BlobFileName"].ToString(), FileMode.OpenOrCreate, FileAccess.Write);

    BinaryWriter writer = new BinaryWriter(fs);

    //reset the index to the beginning of the file

    CurrentIndex = 0;

    BytesReturned = reader.GetBytes(1, //the BlobsTable column indexCurrentIndex, // the current index of the field from which to begin the read operationBlob, // Array name to write tha buffer to0, // the start index of the array to start the write operationBufferSize // the maximum length to copy into the buffer); 

    while (BytesReturned == BufferSize)

    {

        writer.Write(Blob);

        writer.Flush();
        CurrentIndex += BufferSize;

        BytesReturned = reader.GetBytes(1, CurrentIndex, Blob, 0, BufferSize);

    } 

    writer.Write(Blob, 0, (int)BytesReturned);

    writer.Flush(); writer.Close(); 

    fs.Close();

}
 

reader.Close();

SaveCommand.Connection.Close();

To fully understand the concept you need to try to write this code yourself.

Note: The database and the full source code in the source code area with this article.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Amr Monjid
Amr Monjid is a computer programmer from Egypt. He has experience with C#, .Net framework, ASP.NET, Windows Applications, ADO.NET, Xml, Web Services, Custom Controls, and e-commerce web sites. and he is a MCTS: .NET framework 2.0, Windows Application, Distributed Aplication.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
WorkingWithBLOBs.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved