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

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

CREATE TABLE CONTRACTS (
    ID VARCHAR (50),
    CONTRACT_FILE IMAGE
);

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

将文件转换为byte数组
 /// <summary>
        /// 将文件转换为Bytes
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static byte[] File2Bytes(string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read);
            byte[] fileDatas = new byte[fs.Length];
            fs.Read(fileDatas, 0, System.Convert.ToInt32(fs.Length));
            fs.Close();
            return fileDatas;
        }

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

将文件存储到数据库
 /// <summary>
        /// 更新合同文件
        /// </summary>
        /// <param name="id"></param>
        /// <param name="fileBytes"></param>
        /// <returns></returns>
        public bool UpdateContractFile(string id, byte[] fileBytes)
        {
            string sql = "UPDATE CONTRACTS SET CONTRACT_FILE=@CONTRACT_FILE WHERE ID=@ID";
            using (SqlConnection conn = new SqlConnection(this.m_DataAccess.ConnectString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = sql;
                    cmd.Parameters.Clear();

                    cmd.Parameters.Add(new SqlParameter("@CONTRACT_FILE", SqlDbType.Image));
                    cmd.Parameters["@CONTRACT_FILE"].Value = fileBytes;

                    cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.VarChar));
                    cmd.Parameters["@ID"].Value = id;

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

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

通过ID获取文件byte数组
/// <summary>
        /// 获取合同文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public byte[] GetContractFile(string id)
        {
            string sql = "SELECT CONTRACT_FILE FROM CONTRACTS WHERE ID='{0}'";
            sql = string.Format(sql, id);
            object contractFile;
            contractFile = this.m_DataAccess.ExecuteScalar(sql);
            if (contractFile == null)
            {
                return new byte[0];
            }
            else
            {
                return (byte[])contractFile;
            }
        }

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

将byte[]数组存储为Word文件
byte[] fileBytes = this.m_ContractsBusiness.GetContractFile(id);
                if (fileBytes.Length == 0)
                {
                    XMessageBox.ShowError("未找到合同文件!");
                    return;
                }
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "Word文件(*.doc)|*.doc";
                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        string saveFileName = sfd.FileName;
                        int arraysize = new int();//注意这句话
                        arraysize = fileBytes.GetUpperBound(0);
                        FileStream fs = new FileStream(saveFileName, FileMode.OpenOrCreate, FileAccess.Write);
                        fs.Write(fileBytes, 0, arraysize);
                        fs.Close();
                        if (XMessageBox.ShowQuestion("文件下载成功,是否立即打开文件?") ==
                            System.Windows.Forms.DialogResult.Yes)
                        {
                            Process.Start(saveFileName);
                        }
                    }
                    catch (Exception ex)
                    {
                        XMessageBox.ShowError("下载文件失败!");
                    }


你可能感兴趣的:(C#)