Wednesday, October 7, 2009

Saving Binary in SQL Server to PDF file

Well, I'm working on a project where I enable a user to upload a file and store it in SQL Server 2005, and then need to pull it out of the database and save the PDF file to disk using a WinClient app.

System.IO.FileStream fs;                // Writes the binary to a file (*.pdf).
System.IO.BinaryWriter bw; // Streams the binary to the FileStream object.
int bufferSize = 100; // Initial size of the binary buffer.
byte[] outbyte = new byte[bufferSize]; // The binary byte[] buffer to be filled by GetBytes.
long retval; // The bytes returned from GetBytes.
long startIndex = 0; // The starting position in the binary output.
string rec_id = ""; // The id to use in the file name.

while (myReader.Read())
// Get the id.
rec_id = myReader["DocumentationUploadID"].ToString();

// Create a file to hold the output.
fs = new System.IO.FileStream("DocumentID-" + rec_id + ".pdf", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
bw = new System.IO.BinaryWriter(fs);

// Reset the starting byte for the new Binary.
startIndex = 0;

// Read the bytes into outbyte[] and retain the number of bytes returned.
retval = myReader.GetBytes(1, startIndex, outbyte, 0, bufferSize);

// Continue reading and writing while there are bytes beyond the size of the buffer.
while (retval == bufferSize)

// Reposition the start index to the end of the last buffer and fill the buffer.
startIndex += bufferSize;
retval = myReader.GetBytes(1, startIndex, outbyte, 0, bufferSize);

// Write the remaining buffer.
bw.Write(outbyte, 0, (int)retval);

// Close the output file.