Excel 2007 file writer in C# results in a corrupt file
Posted
by Martin
on Stack Overflow
See other posts from Stack Overflow
or by Martin
Published on 2010-04-06T20:59:22Z
Indexed on
2010/04/06
21:03 UTC
Read the original article
Hit count: 503
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.
© Stack Overflow or respective owner