views:

258

answers:

2

Hi,

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.

A: 

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.

Asher
I have tried adjusting the encoding used to write the file out, tried using Unicode, UTF8, UTF7, ANSI, ASCII, plus a couple of suggested code pages referenced in other answers provided to vaguely simellar questions.Content is user generated from a large variety of users, so is completely unpredicable.The OWA Office 2007 issue referenced by Asher does affect the system I am using, but the issue doesn't affect the contents of the file (i.e. once saved to disk Excel will open it without issue).
Martin
+1  A: 

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

Martin