Using a MemoryStream with FileStreamResult possibl

2019-01-26 03:43发布

问题:

I'm using DotNetZip to create a zip file and pass it to a FileResult. On debug, I can verify that the MemoryStream contains a file, but when I run it through FileStreamResult, it returns 0bytes:

public FileResult GetZipFiles(int documentId) {
       var file = fileRepository.Get(documentId);
       var zip = new ZipFile();
       var stream = new MemoryStream();

       var filePath = Path.Combine(UploadsFolder, Path.GetFileName(file.Id));

       zip.AddFile(filePath);
       zip.Save(stream);

       var result = new FileStreamResult(stream, "application/zip") 
                    { FileDownloadName = "hey.zip" };

       return result;
 }

Again, I can verify that stream is not empty, but this will always return the file hey.zip as 0bytes. I must be using MemoryStream wrong here? Or FileStreamResult does something I'm not expecting it to do? I've used FileStreamResult before, but not with MemoryStream.

回答1:

Have you tried setting stream.Position = 0; after you do the zip.Save(stream)?

Also, you might confirm that data is actually being written to the stream. Check stream.Length after zip.Save. If stream.Length is zero, then nothing's being written.