上传文件,MemoryStream 与 FileInfo

发布于 2024-12-23 05:52:07 字数 256 浏览 3 评论 0原文

我必须在我的 ASP.NET Web 应用程序中生成一些文件并将其发送到客户端。 所以我创建了一个使用内存流并将缓冲区发送到 http 响应的方法。

它工作正常,但我刚刚读了另一个代码,那家伙正在使用 fileInfo.txt。因此,如果我理解正确的话,FileInfo 是写入服务器磁盘上的“真实”文件。

那么什么是最好的选择呢? (如果有的话)我必须问我什么问题?与文件大小有关吗?

请注意,我不关心存储文件,一旦发送,我就不必将其放在服务器上。

I have to generate some files in my asp.net web application and send it to the client.
So I made a method who work with a memory stream and send the buffer to the http response.

It is working fine but I just read another code and the guy is using a fileInfo. So if I understand correctly FileInfo is a "real" file written on the server disk.

So what is the best choice? (if there's one) What are questions I have to ask me? Is it about the size of the file?

Note that I don't care about storing the file, once he is send I don't have to have it on the server.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

呆萌少年 2024-12-30 05:52:07

FileInfo 只是一个指向已存储在文件系统上的文件的指针。如果你想访问它的内容,你需要使用流。因此,在您的情况下,如果您不想将文件保存在服务器上,您可以使用 MemoryStream 并将其写入响应。 Stream 也是指向某些数据的指针。 MemoryStream 是指向内存中存储的数据的指针。因此,您需要首先将此数据加载到内存中。

更好的方法是直接分块写入 Response 对象。这样您就不需要将整个文件内容加载到内存中。但这取决于您生成文件的方式。

FileInfo is only a pointer to a file already stored on a file system. If you want to access its contents you need to use a stream. So in your case if you don't want to save the file on the server you could use a MemoryStream and write it to the response. A Stream is also a pointer to some data. A MemoryStream is a pointer to a data stored in memory. So you will need to first load this data in memory.

A better way is to directly write to the Response object in chunks. This way you don't need to load the whole file contents in memory. But this will depend on how you are generating the file.

罪#恶を代价 2024-12-30 05:52:07

为什么不使用 FileUpload 类?如果您需要的只是文件的流,则可以使用 FileUpload.FileContent 属性。但将来,如果您确实关心它并且想要保存它,只需 FileUpload.SaveAs({服务器上的路径})

这样,无论您现在或将来的实现需要如何,您都可以使用相同的类/控件。

有关相关 MSDN 文章 的详细信息。

Why not use the FileUpload class? If all you need is the stream to the file, you can then use FileUpload.FileContent property. But in the future, if you did care about it, and want to save it, it's simply FileUpload.SaveAs({path on server}).

This way you can use the same class/control regardless of your implementation needs now, or in the future.

More info on the relevant MSDN article.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文