Use LINQPAD to write the contents of a BLOB column in your database table to a file
Hey all ! This is my first blog post, so bear with me.
Going to show you a really neat way to get at the binary data stored in a BLOB column of your database table.
I'm going to keep the table simple. Lets assume we have a table that looks something like this (I'm using a SQL Server database):
CREATE TABLE [dbo].[MyBlobs]( [Id] [int] NOT NULL, [Filename] [nvarchar](255) NOT NULL, [BinaryData] [image] NOT NULL )
For this example we can also assume we have 3 rows:
Id=1, Filename="music.mp3", BinaryData=[bytes - lots of them] Id=2, Filename="foo.pdf", BinaryData=[bytes - lots of them] Id=3, Filename="cheese.jpg", BinaryData=[bytes - lots of them]
Lets open LINQPAD and enter the following code into the query window as a "C# Program":
void Main() { var tableRow = MyBlobs .Where (r => r.Id == 2) .SingleOrDefault();
if (tableRow != null) System.IO.File.WriteAllBytes( Path.Combine(@"D:\", tableRow.Filename), tableRow.BinaryData.ToArray());
Console.WriteLine (tableRow); }
The first line is fairly standard LINQ that retrieves the row in the table with Id of 2.
The second line writes the file out to the D: drive.
The trick here is calling ToArray() on the BinaryData column of the row. LINQPAD has done all the work for us to represent each column from the database table as a property on the object returned by the query in the first line.
If we look on our D:\ drive, we will find the file "foo.pdf".
And that's all folks.
PS. There's some great discussion on the oreilly forum about displaying images from your database columns right inside LINQPAD.
Check it out here: http://forums.oreilly.com/topic/21099-displaying-embedded-images-in-linqpad/












