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();
}
}