Home > C# > Exporting blob images from mssql

Exporting blob images from mssql

Although you can use the export tool from microsoft. I just wrote a small C# app to do the same thing. Below is the code.

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.IO;
 
namespace ExportImages
{
	public class Program
	{
		static void Main(string[] args)
		{
			Program program = new Program();
			program.ExportImages();
		}
 
		private void ExportImages()
		{
			string connectionString = String.Format("Server=<servername>; Database=<databasename>; Integrated Security=SSPI");
			using (SqlConnection connection =
					new SqlConnection(connectionString))
			{
				try
				{
					connection.Open();
					SqlDataAdapter data = new SqlDataAdapter(
						@"select Id, Thumbnail from Images", connection);
					DataSet ds = new DataSet("images");
					int recordsFound = data.Fill(ds);
					for (int index = 0; index < recordsFound; index++)
					{
						int id = (int) ds.Tables[0].Rows[index]["Id"];
						byte[] imageData = (byte[]) ds.Tables[0].Rows[index]["Thumbnail"];
						int imageSize = imageData.GetUpperBound(0);
						FileStream fs = new FileStream(@"F:\images\" + id + "_thumbnail.jpg", FileMode.OpenOrCreate, FileAccess.Write);
						fs.Write(imageData, 0, imageSize);
						fs.Close();
					}
				}
				catch (SqlException e)
				{
					Console.WriteLine(e.Message);
				}
				finally
				{
					if (connection.State != ConnectionState.Closed)
					{
						connection.Close();
					}
				}
			}
		}
	}
}
Categories: C# Tags:
  1. No comments yet.
  1. No trackbacks yet.

Time limit is exhausted. Please reload CAPTCHA.