从 C# 中的流对象创建临时文件
给定一个包含 xlsx 文件的流对象,我想将其保存为临时文件,并在不再使用该文件时将其删除。
我想创建一个实现 IDisposable 的类,并将其与 using 代码块一起使用,以便在最后删除临时文件。
知道如何将流保存到临时文件并在使用结束时将其删除吗?
谢谢
Given a stream object which contains an xlsx file, I want to save it as a temporary file and delete it when not using the file anymore.
I thought of creating a class
that implementing IDisposable
and using it with the using
code block in order to delete the temp file at the end.
Any idea of how to save the stream to a temp file and delete it on the end of use?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用 TempFileCollection 类:
这很好与此相关的是,即使抛出异常,由于
using
块,临时文件也能保证被删除。默认情况下,这会将文件生成到系统上配置的临时文件夹中,但您也可以在调用 TempFileCollection 构造函数时指定自定义文件夹。You could use the TempFileCollection class:
What's nice about this is that even if an exception is thrown the temporary file is guaranteed to be removed thanks to the
using
block. By default this will generate the file into the temporary folder configured on the system but you could also specify a custom folder when invoking theTempFileCollection
constructor.您可以使用 Path.GetTempFileName() 获取临时文件名,创建一个 FileStream 来写入它并使用 Stream.CopyTo 复制所有内容将输入流中的数据写入文本文件:
You can get a temporary file name with
Path.GetTempFileName()
, create aFileStream
to write to it and useStream.CopyTo
to copy all data from your input stream into the text file:这里的另一种方法是:
这样文件将在关闭后被删除。
编辑:
如果您不需要流存在太长的时间(例如:仅单个写入操作或单个循环写入...),您可以按照建议将此流包装到 using 块中。这样您就不必手动处理它了。
代码如下:
Another approach here would be:
This way the file will get removed after closing.
Edit:
If you don't need the stream to live too long (eg: only a single write operation or a single loop to write...), you can, as suggested, wrap this stream into a using block. With that you won't have to dispose it manually.
Code would be like:
编辑:
抱歉,也许只是我,但我可以发誓,当您最初发布问题时,您没有关于实现 IDisposable 等的类的所有详细信息...无论如何,我不太确定您是什么正在问你的(编辑过的?)问题。但是这个问题:
知道如何将流保存到临时文件并在使用结束时删除它吗?
非常简单。对于“.NET C# Stream to File”等,任何数量的谷歌结果都会返回。EDIT:
Sorry, maybe it's just me, but I could have sworn that when you initially posted the question you didn't have all that detail about a class implementing IDisposable, etc... anyways, I'm not really sure what you're asking in your (edited?) question. But this question:
Any idea of how to save the stream to temp file and delete it on the end of use?
is pretty straight-forward. Any number of google results will come back for ".NET C# Stream to File" or such.我只是建议使用
Path.GetTempFileName()
创建文件。但其他取决于您的使用情况,例如,如果您想在临时创建者类中创建它并在那里使用它,最好使用using
关键字。I just suggest for creating file use
Path.GetTempFileName()
. but others depends on your usage senario, for example if you want to create it in your temp creator class and use it just there, it's good to useusing
keyword.