Zip file created directly from memorystream is empty and getting error "Cannot access a closed Stream" in C#

Thomas Ansamma, ITP71, BUZ 21 Reputation points
2022-02-18T05:52:00.323+00:00

I am trying to create a zip file with one text file and send as FileStreamResult.
The zip file is empty and getting error "Cannot access a closed Stream".

If I write the memorystream to byte array, I am getting text file inside zipped file.
But I wanted to avoid converting to byte array as it will take extra memory.

Is there a way to generate zip file without using ToArray() method?

Sample code below :

     return File(outStream, "application/zip", "MyFile.zip");
     ActionResult Index()
     {
         using var outStream = new MemoryStream();
         using (var archive = new System.IO.Compression.ZipArchive(outStream, System.IO.Compression.ZipArchiveMode.Create, true))
         {
            var fileInArchive = archive.CreateEntry("MyFile.txt", System.IO.Compression.CompressionLevel.Optimal);
            using var entryStream = fileInArchive.Open();
            using var fileToCompressStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("HelloWorld"));
            fileToCompressStream.CopyTo(entryStream);
        }
        return File(outStream, "application/zip", "MyFile.zip");

    //var compressedBytes = outStream.ToArray();
    //return File(compressedBytes, "application/zip", "MyFile.zip");
}
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2022-02-18T06:17:05.37+00:00

    Maybe you must remove the using for outStream and do this:

    . . .
    outStream.Position = 0;
    return File(outStream, "application/zip", "MyFile.zip");

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.