Search This Blog

Thursday, October 21, 2010

Read SQL blob as byte array and save to File

This is an example that fetches a report binary stored as a blob in a SQL server table.

tbBillingPaperReport: SQL Server table where report binary is stored in column Report file.
Writes files root folder the current user document and settings folder
example:  C:\Documents and Settings\Gkindel\



using System;
using System.IO;
using System.Data.SqlClient;

private const string _SQLConnectionString = "Data Source={0};Initial Catalog={1};User ID={2};Password={3};";

SqlConnection db = new SqlConnection(string.Format(_SQLConnectionString,"ServerName", "DBName", "user", "password"));

db.Open();

SqlCommand cmd = new SqlCommand("SELECT ReportID, FileVersion, ReportName, ReportFile FROM tbBillingPaperReport", db);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
adapter.Fill(table);

string savePath = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.Personal)).ToString();                    

foreach (DataRow row in table.Rows)
{
     byte[] report = row["ReportFile"] as byte[];
     string filename = string.Format("0}\\{1}.rpt",savePath,row["ReportName"]);                           

     BinaryWriter writer = new BinaryWriter(File.Open(filename,FileMode.Create));
     writer.Write(report);
     writer.Close();
}



No comments: