using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
//把文件写入数据库
public void add(string pathName)
{
FileStream fs = new FileStream(pathName, FileMode.Open, FileAccess.Read);
byte[] buffByte = new byte[fs.Length];
fs.Read(buffByte, 0, (int)fs.Length);
fs.Close();
fs = null;
SqlConnection conn = new SqlConnection(@"data source=test;uid=sa;pwd=test;database=test");
string sqlstr = @"Insert into table1(doc) values(@img)";
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlstr;
cmd.Connection = conn;
cmd.Parameters.Add("@img", System.Data.SqlDbType.Image);
cmd.Parameters[0].Value = buffByte;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
buffByte = null;
}
//从数据库读出文件
public void save(string fileName)
{
SqlConnection conn = new SqlConnection(@"data source=test;uid=sa;pwd=test;database=test");
conn.Open();
SqlCommand cmd = new SqlCommand("select top 1 doc from table1", conn);
SqlDataReader reader = cmd.ExecuteReader();
byte[] buffByte = null;
if (reader.Read())
{
buffByte = (byte[])reader[0];
}
reader.Close();
conn.Close();
FileStream fs;
FileInfo fi = new FileInfo(fileName);
fs = fi.OpenWrite();
fs.Write(buffByte, 0, buffByte.Length);
fs.Close();
}
static void Main(string[] args)
{
Program p = new Program();
p.add(@"C:/test.doc");
p.save(@"C:/test1.doc");
}
}
}
//bs保存文件:
protected void downloadFile(string strYYBH)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["LIMSConnectionString"].ToString());
conn.Open();
SqlCommand cmd = new SqlCommand("select top 1 F_file,F_fileName from FileDoc where F_YYBH='" + strYYBH.ToString().Trim() + "'", conn);
SqlDataReader reader = cmd.ExecuteReader();
byte[] buffByte = null;
string fileName = string.Empty;
if (reader.Read())
{
buffByte = (byte[])reader[0];
fileName = reader[1].ToString();
}
reader.Close();
conn.Close();
Response.ContentType = "application/octet-stream/unknow";
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
this.Response.Clear();
System.IO.Stream fs = this.Response.OutputStream;
fs.Write(buffByte, 0, buffByte.Length);
fs.Close();
this.Response.End();
}