简体   繁体   English

检索时保存到图像列的文档已损坏

[英]Document saved to an image column gets corrupted when retrieved

I am saving documents ( *.docx, *.doc, *.pdf ) to an Image column in a SQL Server 2012 database. 我将文档( *.docx, *.doc, *.pdf )保存到SQL Server 2012数据库中的“ Image列。 Here is the partial table script (for brevity, I removed a lot of columns) 这是部分表脚本(为简便起见,我删除了很多列)

[DocId] [int] IDENTITY(1,1) NOT NULL,
[DocDate] [datetime] NOT NULL DEFAULT (getdate()),
[DocName] [varchar](255) NOT NULL  DEFAULT (''),
[DocObject] [image] NOT NULL

The documents are being saved using this code in C# 使用此代码在C#中保存文档

using (Stream docStream = UploadResume.PostedFile.InputStream)
{
    Int32 docSize = (Int32)docStream.Length;
    byte[] docBytes = new byte[docSize + 1];
    docStream.Read(docBytes, 0, docSize);
    SaveDoc(docId, UploadResume.PostedFile.FileName.Trim(), docBytes);
}

SaveDoc is a procedure that inserts the data into the table. SaveDoc是一个将数据插入表中的过程。 I removed code for saving other fields of data for brevity. 为了简便起见,我删除了保存其他数据字段的代码。

I am retrieving data into a DataTable (dt). 我正在将数据检索到DataTable(dt)中。 I am saving the contents of the document to file system using the following C# code: 我正在使用以下C#代码将文档的内容保存到文件系统中:

byte[] docBytes = (byte[])(dt.Rows[0]["DocObject"]);
var fileName = dt.Rows[0]["DocName"].ToString();
File.WriteAllBytes(Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Documents\\{DateTime.Now.ToString("yyyyMMdd")}"), $"{fileName}"), docBytes);

I am able to save an MS Word document to the db, retrieve it from the db and save it to file system successfully. 我能够将MS Word文档保存到数据库中,从数据库中检索它并将其成功保存到文件系统中。 However when I open the document in MS Word, I get an error message indicating that the file is corrupted. 但是,当我在MS Word中打开文档时,收到一条错误消息,指示文件已损坏。 PDF files are save and open fine without issues. PDF文件可以保存并可以正常打开。 Microsoft Word documents are not. Microsoft Word文档不是。

Thank you for all of your help. 感谢您的所有帮助。 I put the extra byte for testing something else and forgot to remove it later. 我把多余的字节用于测试其他内容,却忘了稍后将其删除。 That was the problem. 那就是问题所在。 I removed it and all works fine. 我删除了它,一切正常。 I know that the image column type is deprecated. 我知道不推荐使用图像列类型。 However, the database is part of a third party commercial product and can't be modified without breaking the commercial application. 但是,该数据库是第三方商业产品的一部分,在不破坏商业应用程序的情况下不能对其进行修改。 Thanks for pointing out though. 感谢您指出。 Appreciate it. 欣赏它。 I can't yet accept the answer and vote since I don't have enough reputation points. 由于我的信誉分数不足,因此我无法接受答案和投票。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM