using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
class Sample
{
public static void Main()
{
SqlConnection pubsConn = new SqlConnection("Data Source=diana//diana;Integrated Security=SSPI;Initial Catalog=pubs;");
SqlCommand logoCMD = new SqlCommand("select pub_id,logo from pub_info",pubsConn);
//保存blob文件
FileStream fs;
BinaryWriter bw;
//緩衝區大小
int bufferSize = 100;
//緩衝區
byte[] outbyte = new byte[bufferSize];
long reval;
long startIndex = 0;
string pub_id = "";
//打開鏈接
pubsConn.Open();
SqlDataReader myReader = logoCMD.ExecuteReader(CommandBehavior.SequentialAccess);
while(myReader.Read())
{
//獲得出版商id,必須在讀取blob列之前獲取
pub_id = myReader.GetString(0);
//創建輸出文件
fs = new FileStream("logo" + pub_id + ".bmp",FileMode.OpenOrCreate,FileAccess.Write);
bw = new BinaryWriter(fs);
//重置起始位置
startIndex = 0;
//第一次讀取blob到緩衝區
retval = myReader.GetBytes(1,startIndex,outbyte,0,bufferSize);
//讀完爲止
while(retval == bufferSize)
{
bw.Write(outbyte);
bw.Flush();
//重定位
startIndex += bufferSize;
retval = myReader.GetBytes(1,startIndex,outbyte,0,bufferSize);
}
//最後把不足緩衝區大小的緩衝區寫入文件
bw.Write(outbyte);
bw.Flush();
//關閉輸出文件
bw.Close();
fs.Close();
}
//關閉讀取器和鏈接
myReader.Close();
pubsConn.Close();
}
}