简体   繁体   中英

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. 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#

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. I removed code for saving other fields of data for brevity.

I am retrieving data into a DataTable (dt). I am saving the contents of the document to file system using the following C# code:

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. However when I open the document in MS Word, I get an error message indicating that the file is corrupted. PDF files are save and open fine without issues. Microsoft Word documents are not.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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