Tuesday, July 3, 2007

Reading binary data from Sql sever Database C# Code

//Define Memory Stream
MemoryStream msMemoryStreams = new MemoryStream();
DBConnection conn = new DBConnection();
SqlDataReader sdrReader;
sdrReader = conn.GetDownloadFile("GetFilesDownlod", Convert.ToInt32(DownloadID));
sdrReader.Read();
// Reading the IMAGE data filed data to byte array
// sdrReader.GetBytes(XXX, 0, null, 0, int.MaxValue) , XXX defines the colum number (Zero based)for image data ;see SQL query


byte[] byteData = new Byte[(sdrReader.GetBytes(3, 0, null, 0, int.MaxValue))];
sdrReader.GetBytes(3, 0, byteData, 0, byteData.Length);
//Get the file name
// sdrReader.GetString(XXX) , XXX defines the colum number (Zero based) for file name ;see SQL query

string strOutputFileName = sdrReader.GetString(0);
//get file extension from sqldatareader

string Extension = "." + sdrReader["Extension"].ToString();
strOutputFileName = strOutputFileName+Extension;
msMemoryStreams.Write(byteData, 0, byteData.Length);
//Convert the memorystream to an array of bytes.
byte[] byteArray = msMemoryStreams.ToArray();
//Clean up the memory msMemoryStreams

msMemoryStreams.Flush();
msMemoryStreams.Close();
// Clear all content output from the buffer msMemoryStreams
Response.Clear();
// Add a HTTP header to the output msMemoryStreams that specifies the default filename
// for the browser's download dialog
Response.AddHeader("Content-Disposition", "attachment; filename=" + strOutputFileName);
// Add a HTTP header to the output msMemoryStreams that contains the
// content length(File Size). This lets the browser know how much data is being transfered


Response.AddHeader("Content-Length", byteArray.Length.ToString());
// Set the HTTP MIME type of the output msMemoryStreams
Response.ContentType = sdrReader["ContentType"].ToString();
sdrReader.Close();
// Write the data out to the client.

Response.BinaryWrite(byteArray);
//to stoping adding unwanted html coding

Response.End();

2 comments:

Sid Shrivastav said...

Hey Sanjeewa, Have you worked with editing images that are stored in a database as a Binary Data? I am supposed to allow the user to write test like SOLD on the images they want to write and later save that to the database as Binary data. All the images come from the database.
Thanks

SS - LK said...

hi friend please refer my blog..i think i already added some code in my blog which you need..

F.Y.I my chat id is=sanjeewa070@yahoo.com