Maybe you must remove the using for outStream and do this:
. . .
outStream.Position = 0;
return File(outStream, "application/zip", "MyFile.zip");
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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");
}
Maybe you must remove the using for outStream and do this:
. . .
outStream.Position = 0;
return File(outStream, "application/zip", "MyFile.zip");