C#實現在Sql Server中儲存和讀取Word檔案

來源:互聯網
上載者:User

要實現在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("下載檔案失敗!");                    }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.