Reading varbinary data of SQL Server into MemoryStream of C#

Posted by Poster under C# category on | Views : 19322
Following code snippet show how to read the VarBinary data of SQL Server into C#.

Lets suppose you have a DataTable in which you are loading the data from SQL Server database using SqlDataAdapter object. For each DataRow of the DataTable you want to get the VarBinary data into MemoryStream for further processing, you can use following code snippet.

using (MemoryStream memStream = new MemoryStream((byte[])row["VarBinaryDataField"]))


Hope this will help.

Thank you.

Comments or Responses

Posted by: Samarmir on: 5/29/2012 Level:Starter | Status: [Member] | Points: 10
Just want to say big thank!
You saved my day :)

If anyone has a ms sql table with a column that has following datatype varbinary(MAX)
then they can use following method to decode and retrieve the value inside the column (lets call the column for Source)

foreach (DataRow row in myDataTable.Rows)
MemoryStream memStream = new MemoryStream((byte[])row["Source"]);
var htmlWebPageRow = Encoding.GetEncoding(65001).GetString(memStream.ToArray());

Login to post response