简体   繁体   中英

C# MemoryStream.CopyTo(fileStream) adding extra bytes and corrupting OpenXML file

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?

(Documenting per comments.) The issue could be explained by the file replacing an existing file of length 2014 bytes.

Creating a file stream using a mode of FileMode.OpenOrCreate is equivalent to using FileMode.Open if the referenced file exists. If the length of the memory stream is less than the length of the existing file, the existing file will not be truncated to the length of the memory stream; in this case, if N is the length of the memory stream, the first N bytes of the existing file will be overwritten with the contens of the memory stream, and the remaining bytes will persist from the original file.

Creating the file stream with a file mode of FileMode.Create will replace the existing file entirely (if one exists), eliminating any possibility that the new file will contain remnants of the existing file.

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