开发者

Excel 2007 file writer in C# results in a corrupt file

开发者 https://www.devze.com 2022-12-25 16:35 出处:网络
I am using a BinaryReader to read an Excel 2007 file from an Exchange mailbox using a OWA, the file is then written to disk using a BinaryWriter.My problem is that the two files don\'t match when the

I am using a BinaryReader to read an Excel 2007 file from an Exchange mailbox using a OWA, the file is then written to disk using a BinaryWriter. My problem is that the two files don't match when the writer finishes. Worse still Excel 2007 won't open the writen file.

Previously Excel 2003 has had no problem with the solution below. And Excel 2007 doesn't have an issue if the file is an Excel 2003开发者_运维知识库 format file, only if the file format is Excel 2007 (*.xlsx).

BinaryReader:

using(System.IO.Stream stream = resource.GetInputStream(attachedFiles[k].Address))
{
    using(System.IO.BinaryReader br = new System.IO.BinaryReader(stream))
    {
        attachment.Data = new byte[attachedFiles[k].Size];
        int bufPosn=0, len=0;
        while ((len = br.Read( attachment.Data, bufPosn, attachment.Data.Length-bufPosn )) > 0)
        {
            bufPosn += len;
        }
        br.Close();
    }
}

BinaryWriter:

FileStream fs = new FileStream(fileName, FileMode.Create);
BinaryWriter binWriter = new BinaryWriter(fs);
binWriter.Write( content, 0, content.Length );
binWriter.Close();
fs.Close();

Suggestions gratfully received.


This issue was caused by the value being returned by attachedFiles[k].Size which was far inexcess of the actual file size. Excel 2003 files it seems are unaffected by this, but Excel 2007 files are vulnerable due to their compressed nature (the decompression routine obviously sees the file differently).

Once I corrected the size of the buffer the files are fine.

Thanks for the suggestions


There is an issue with IE8 and OWA but I am not sure if it applies in your case.

Checkout this site which also has a link to this site. They basically explain how to get around the problem of download xmlx and docx files with an OWA.

0

精彩评论

暂无评论...
验证码 换一张
取 消