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