将word文档保存到数据库中

2024-12-15 16:40:45
推荐回答(1个)
回答1:

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