简体   繁体   English

在c#中从流对象创建临时文件

[英]Create a temporary file from stream object in c#

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. 给定一个包含xlsx文件的流对象,我想将其保存为临时文件,并在不再使用该文件时将其删除。

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. 我想创建一个实现IDisposableclass ,并将其与using代码块一起using ,以便最后删除临时文件。

Any idea of how to save the stream to a temp file and delete it on the end of use? 知道如何将流保存到临时文件并在使用结束时将其删除?

Thanks 谢谢

You could use the TempFileCollection class: 您可以使用TempFileCollection类:

using (var tempFiles = new TempFileCollection())
{
    string file = tempFiles.AddExtension("xlsx");
    // do something with the file here 
}

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. 这有什么好处,即使抛出异常,由于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 the TempFileCollection constructor. 默认情况下,这会将文件生成到系统上配置的临时文件夹中,但您也可以在调用TempFileCollection构造函数时指定自定义文件夹。

You can get a temporary file name with Path.GetTempFileName() , create a FileStream to write to it and use Stream.CopyTo to copy all data from your input stream into the text file: 您可以使用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);
}

Another approach here would be: 这里的另一种方法是:

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

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: 代码如下:

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

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. 对不起,也许这只是我,但我可以发誓,当你最初发布问题时,你没有关于实现IDisposable等的类的详细信息......不管怎样,我不确定你在问什么在你的(编辑?)问题中。 But this question: Any idea of how to save the stream to temp file and delete it on the end of use? 但是这个问题: 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. 任何数量的谷歌搜索结果都将返回“.NET C#Stream to File”等。

I just suggest for creating file use Path.GetTempFileName() . 我只是建议创建文件使用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 use using keyword. 但是其他人依赖于你的使用情况,例如,如果你想在你的临时创建者类中创建它并在那里使用它,那么using关键字是很好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM