C#实现在Sql Server中存储和读取Word文件

要实现在Sql Server中实现将文件读写Word文件,需要在要存取的表中添加Image类型的列,示例表结构为:

CREATE TABLE CONTRACTS (

    ID VARCHAR (50),

    CONTRACT_FILE IMAGE

);

要将Word文件存储到数据库的CONTRACT_FILE字段中,需要将文件转换为byte数组,具体代码如下:

将文件转换为byte数组
 1  /// <summary>

 2         /// 将文件转换为Bytes

 3         /// </summary>

 4         /// <param name="fileName"></param>

 5         /// <returns></returns>

 6         public static byte[] File2Bytes(string fileName)

 7         {

 8             FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read);

 9             byte[] fileDatas = new byte[fs.Length];

10             fs.Read(fileDatas, 0, System.Convert.ToInt32(fs.Length));

11             fs.Close();

12             return fileDatas;

13         }

然后将转换完成的byte[]存储到数据库的对应字段:

将文件存储到数据库
 1  /// <summary>

 2         /// 更新合同文件

 3         /// </summary>

 4         /// <param name="id"></param>

 5         /// <param name="fileBytes"></param>

 6         /// <returns></returns>

 7         public bool UpdateContractFile(string id, byte[] fileBytes)

 8         {

 9             string sql = "UPDATE CONTRACTS SET CONTRACT_FILE=@CONTRACT_FILE WHERE ID=@ID";

10             using (SqlConnection conn = new SqlConnection(this.m_DataAccess.ConnectString))

11             {

12                 conn.Open();

13                 using (SqlCommand cmd = new SqlCommand())

14                 {

15                     cmd.Connection = conn;

16                     cmd.CommandText = sql;

17                     cmd.Parameters.Clear();

18 

19                     cmd.Parameters.Add(new SqlParameter("@CONTRACT_FILE", SqlDbType.Image));

20                     cmd.Parameters["@CONTRACT_FILE"].Value = fileBytes;

21 

22                     cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.VarChar));

23                     cmd.Parameters["@ID"].Value = id;

24 

25                     return cmd.ExecuteNonQuery() > 0 ? true : false;

26                 }

27             }

28         }

要读取数据库中存储的Word文件,需要先将Image类型的字段转换为bytes[],具体代码如下:

通过ID获取文件byte数组
 1 /// <summary>

 2         /// 获取合同文件

 3         /// </summary>

 4         /// <param name="id"></param>

 5         /// <returns></returns>

 6         public byte[] GetContractFile(string id)

 7         {

 8             string sql = "SELECT CONTRACT_FILE FROM CONTRACTS WHERE ID='{0}'";

 9             sql = string.Format(sql, id);

10             object contractFile;

11             contractFile = this.m_DataAccess.ExecuteScalar(sql);

12             if (contractFile == null)

13             {

14                 return new byte[0];

15             }

16             else

17             {

18                 return (byte[])contractFile;

19             }

20         }

在获取到文件的byte[]后,将该文件通过文件流操作存储为Word文件,具体代码如下:

将byte[]数组存储为Word文件
 1 byte[] fileBytes = this.m_ContractsBusiness.GetContractFile(id);

 2                 if (fileBytes.Length == 0)

 3                 {

 4                     XMessageBox.ShowError("未找到合同文件!");

 5                     return;

 6                 }

 7                 SaveFileDialog sfd = new SaveFileDialog();

 8                 sfd.Filter = "Word文件(*.doc)|*.doc";

 9                 if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)

10                 {

11                     try

12                     {

13                         string saveFileName = sfd.FileName;

14                         int arraysize = new int();//注意这句话

15                         arraysize = fileBytes.GetUpperBound(0);

16                         FileStream fs = new FileStream(saveFileName, FileMode.OpenOrCreate, FileAccess.Write);

17                         fs.Write(fileBytes, 0, arraysize);

18                         fs.Close();

19                         if (XMessageBox.ShowQuestion("文件下载成功,是否立即打开文件?") ==

20                             System.Windows.Forms.DialogResult.Yes)

21                         {

22                             Process.Start(saveFileName);

23                         }

24                     }

25                     catch (Exception ex)

26                     {

27                         XMessageBox.ShowError("下载文件失败!");

28                     }

 

你可能感兴趣的:(SQL Server)