Extracting Image Files from SQL Server

There are a number of different plugins and tools which can export image data in hex format from an MS SQL server to an actual file on the harddrive. If you have Visual Studio installed, however, the easiest way is to just write a small console program to select the data from the image column and save it to a file. For example:

static void Main(string[] args)
{
try
{
SqlConnection thisConnection = new SqlConnection(@"Server=192.168.1.1,1433;database=MyDb;User id=sa;Password=JdjdUD78!;");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "SELECT ImageData FROM [MyDatabase].[dbo].[Images] where ID = 1";
byte[] imgBytes = (byte[]) thisCommand.ExecuteScalar();
FileStream fs = new FileStream(@"C:\temp\image.jpg", FileMode.CreateNew, FileAccess.Write);
fs.Write(imgBytes, 0, imgBytes.Length);
fs.Flush();
fs.Close();
thisConnection.Close();
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}