Saturday, July 21, 2007

How to retrieve the blob object in WinForms to physical location with "Binary Streaming" enabled ?

See the snippet below, how it works!!


SqlConnection Conn = new SqlConnection("<>");
SqlCommand Cmd = new SqlCommand("select docobject, filetype,docname from documents where docid = 23", Conn);
Cmd.CommandType = CommandType.Text;
Conn.Open();
SqlDataReader Reader = Cmd.ExecuteReader(CommandBehavior.CloseConnection);
//
string DocumentName = null;
FileStream FStream = null;
BinaryWriter BWriter = null;
//
//
//
byte[] Binary = null;
const int ChunkSize = 100;
int SizeToWrite = 0;
MemoryStream MStream = null;
//
while (Reader.Read())
{
DocumentName = Reader["docname"].ToString();
// Create a file to hold the output.
FStream = new FileStream(@"c:\" + DocumentName, FileMode.OpenOrCreate, FileAccess.Write);
BWriter = new BinaryWriter(FStream);
Binary = (Reader["docobject"]) as byte[];
SizeToWrite = ChunkSize;
MStream = new MemoryStream(Binary);
//
for (int i = 0; i < Binary.GetUpperBound(0) - 1; i = i + ChunkSize)
{
if (i + ChunkSize >= Binary.Length) SizeToWrite = Binary.Length - i;
byte[] Chunk = new byte[SizeToWrite];
MStream.Read(Chunk, 0, SizeToWrite);
BWriter.Write(Chunk);
BWriter.Flush();
}
BWriter.Close();
FStream.Close();
}
FStream.Dispose();
}

6 comments:

Shum said...

Hi there!

Is the first half of the code for writing/ saving the blob to database? and the bottom part for retrieval?

Shum said...

Hi there!

Is the first half of the code for writing/ saving the blob to database? and the bottom part for retrieval?

dotNetSoldier said...

No, it is just for retrieving BLOB from database in winforms. To get more info about dump and retrieve BLOB in asp.net, see my article http://www.codeproject.com/KB/database/Store_and_manipulat_BLOBs.aspx

Unknown said...

I have a problem when trying to access a *.docx file from a blob. The code works well for *.doc, but not so much for the Office 2007 format. Any ideas?

Guy Bailey said...

Tried your code today, and it worked great. Thanks a million for posting!

Guy Bailey said...

Tried your code today, and it worked great. Thanks a million for posting!