首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# 將文件存入 SQL 再讀取,.docx 損壞但可打開的排查

     編輯:程式設計綜合問答

現象

doc/pdf 正常,docx 下載後 Word 提示「文件損壞」,但點擊「是」仍能打開內容完整。

可能原因

  • 文件流未完整寫入/讀取:如未 Flush()、Close(),或讀取時截斷。
  • 編碼/字符集處理不當:二進制數據被當作文本處理(如用 Encoding.GetString)。
  • SQL 字段長度不足:`varbinary(max)` 未用,導致截斷。
  • HTTP 響應頭缺失:`Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document`、`Content-Length`。

排查步驟

  1. 用 WinDiff / Beyond Compare 對比原始文件與下載文件的二進制差異。
  2. 檢查文件大小是否一致;不一致則為傳輸/存儲環節丟失字節。
  3. 確保存取代碼使用 BinaryReader/Writer 或 FileStream,無任何文本編碼轉換。
  4. 下載端設置正確 MIME 類型與 `Content-Disposition: attachment`。

關鍵代碼片段

// 存入
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (var ms = new MemoryStream()) {
    fs.CopyTo(ms);
    cmd.Parameters.Add("@data", SqlDbType.VarBinary, -1).Value = ms.ToArray();
}

// 讀取並下載
byte[] data = (byte[])cmd.ExecuteScalar();
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
Response.AddHeader("Content-Disposition", "attachment; filename=xxx.docx");
Response.BinaryWrite(data);
Response.End();
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved