I'm using OpenXML to generate an Excel spreadsheet.
I'm generating the spreadsheet in a MemoryStream; the caller is writing writing out the actual file. For example, my .Net Core controller will return the memory stream as a FileResult. At the moment, I've got a standalone Console mode program that's writing a FileStream.
PROBLEM: I'm getting extra bytes at the end of the file. Since an OpenXml .xlsx file is a .zip file, the extra bytes effectively corrupt the file.
Program.cs:
using (MemoryStream memoryStream = new MemoryStream())
{
OpenXMLGenerate(memoryStream, sampleData);
long msPos = memoryStream.Position; // Position= 1869: Good!
memoryStream.Position = 0;
using (FileStream fs = new FileStream("myfile.xlsx", FileMode.OpenOrCreate))
{
memoryStream.WriteTo(fs);
long fsPos = fs.Position; // Position= 1869: Good!
}
// Myfile.xlsx filesize= 2014, not 1869! Bad!!!
}
When I open the file in 7-Zip, it it says:
Warnings: There are some data after the end of the payload data
Physical Size: 1869
Tail Size: 145
When I try to open it as a .zip file, Windows says:
The Compressed (zipped) folder is invald.
Q: Any idea why I'm getting a 2014 byte file, instead of 1869 bytes?
Q: What can I do about it?
FileStreamwithFileMode.Createinstead ofFileMode.OpenOrCreateresult in the same issue? - drfFileMode.Create: and it worked perfectly. The memory stream, filestream ... and resulting file are all now 1867 bytes (correct!). NOT 1869, and certainly not 2014. Q: Why???? If you post a response, I'd be happy to upvote/accept it. - FoggyDayFileMode.OpenOrCreateis equivalent toFileMode.Openif the file already exists. The operation likely overwrote the first 1869 bytes of the existing file, while leaving the remainder of the existing file intact. UsingFileMode.Createwould ensure that the old file (if one exists) is entirely replaced. - drf