Reading binary data (image fields) from SQL Server 2005

By John Bowen, 28 August, 2008

I'm working on a project which requires me to read (with C#) existing SQL Server 2005 'Image' datatype data, making it useful to the end user in an ASP.NET application. The trouble is, the mime type for the data stored in each row is not stored...there isn't an easy way to tell, in advance, if the data I'm pulling out is a pdf, gif, jpg, zip, docx, xml, bmp or some other file type.

Looking closely at the stored data, I noticed that they start with consistent values (headers), and there are only a handful of different headers there.

Examples:
0x1F8B08....
0X255044....
0XFFD8FF....

A few Google searches turned up this article/chart, where I confirmed that those headers identify the type of binary file that's stored.

Once that's handled, you can change the Response FileType header of the web page, then Response.BinaryWrite() the data, and the user gets what was stored! If the browser can handle the filetype (like xml, txt, pdf), it just displays it; if not, the file download dialog pops up and offers options for viewing/saving the file.

A few other articles I found alluded to 'magic numbers' or 'magic headers'. They look like they might be talking about that same leading header...but I wasn't able to find an example that would lead me along.

Filtered HTML

  • Web page addresses and email addresses turn into links automatically.
  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.