给定一个包含xlsx文件的流对象,我想将其保存为临时文件,并在不再使用该文件时将其删除。
我想创建一个class
来实现IDisposable
并将其与using
代码块一起使用,以便在最后删除临时文件。
如何将流保存到临时文件并在使用结束时将其删除?
由于
答案 0 :(得分:25)
您可以使用TempFileCollection类:
using (var tempFiles = new TempFileCollection())
{
string file = tempFiles.AddExtension("xlsx");
// do something with the file here
}
这有什么好处,即使抛出异常,由于using
块,保证临时文件被删除。默认情况下,这会将文件生成到系统上配置的临时文件夹中,但您也可以在调用TempFileCollection
构造函数时指定自定义文件夹。
答案 1 :(得分:7)
您可以使用Path.GetTempFileName()
获取临时文件名,创建一个FileStream
来写入,并使用Stream.CopyTo
将输入流中的所有数据复制到文本文件中:
var stream = /* your stream */
var fileName = Path.GetTempFileName();
try
{
using (FileStream fs = File.OpenWrite(fileName))
{
stream.CopyTo(fs);
}
// Do whatever you want with the file here
}
finally
{
File.Delete(fileName);
}
答案 2 :(得分:7)
这里的另一种方法是:
string fileName = "file.txt";
int bufferSize = 4096;
var fileStream = System.IO.File.Create(fileName, bufferSize, System.IO.FileOptions.DeleteOnClose)
// now use that fileStream to save the xslx stream
这样,文件将在关闭后删除。
如果您不需要流过长时间(例如:只有一个写操作或单个循环来写...),您可以按照建议将此流包装到使用块中。这样您就不必手动处理它。
代码就像:
string fileName = "file.txt";
int bufferSize = 4096;
using(var fileStream = System.IO.File.Create(fileName, bufferSize, System.IO.FileOptions.DeleteOnClose))
{
// now use that fileStream to save the xslx stream
}
答案 3 :(得分:1)
// Get a random temporary file name w/ path:
string tempFile = Path.GetTempFileName();
// Open a FileStream to write to the file:
using (Stream fileStream = File.OpenWrite(tempFile)) { ... }
// Delete the file when you're done:
File.Delete(tempFile);
编辑:
抱歉,也许只是我,但我可以发誓,当你最初发布问题时,你没有关于实现IDisposable等的类的详细信息......不管怎样,我不确定你是什么问你的(编辑?)问题。但是这个问题:Any idea of how to save the stream to temp file and delete it on the end of use?
非常简单。任何数量的谷歌搜索结果都将返回“.NET C#Stream to File”等。
答案 4 :(得分:0)
我建议您创建文件使用Path.GetTempFileName()
。但是其他人依赖于你的使用情况,例如,如果你想在你的临时创建者类中创建它并在那里使用它,最好使用using
关键字。