使用具有FileStreamResult一个MemoryStream可能吗? [英] Using a MemoryStream with FileStreamResult possible?

查看:430
本文介绍了使用具有FileStreamResult一个MemoryStream可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用DotNetZip创建一个zip文件,并将其传递给FileResult。在调试,我可以确认的MemoryStream包含一个文件,但是当我通过FileStreamResult运行它,它会返回0bytes:

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;
 }

同样,我可以验证该流不为空,但是这将永远文件 hey.zip 返回为0bytes。我必须使用的MemoryStream 错在这里?或 FileStreamResult 没有什么我没想到它呢?我使用 FileStreamResult 之前,而与的MemoryStream

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.

推荐答案

您是否尝试过设置 stream.Position = 0; 你这样做后, zip.Save(流)

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

此外,您可能确认的数据实际上是被写入流。检查 stream.Length zip.Save 。如果 stream.Length 为零,则什么也没有被写入。

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.

这篇关于使用具有FileStreamResult一个MemoryStream可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆