Coding Dilemas

Thursday, June 08, 2006

C# DataTable value to byte[] array

Being a noob sucks, so this wasn't a lot of fun. I need to RTFM i guess.
So the simplest task in the world. Convert blob data from SQL into a byte array and output it to the browser via Response.BinaryWrite. The problem was I was using a dataSet not the usual dataReader class. After much frustration and google searching the solution was one line of code.

Byte[] bytes = (Byte[])ds.Tables[0].Rows[0][0];


The full code to output a file to the browser from C# via ASP.NET is here:
Response.AddHeader("Content-disposition", Server.UrlEncode(fileName));
Response.ContentType = "application/octet-stream";
Response.WriteFile(fileName);

From a database
Byte[] bytes = (Byte[])ds.Tables[0].Rows[0][0];
Response.AddHeader("Content-disposition", Server.UrlEncode(fileName));
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(bytes);

If you've found this post hopefully you can do the other stuff you need to already. Like figuring out the filename and all that. email me if you need help.