Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

like image 661
Yair Nevet Avatar asked Oct 23 '11 15:10

Yair Nevet


2 Answers

You could use the TempFileCollection class:

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. 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.

like image 52
Darin Dimitrov Avatar answered Oct 05 '22 22:10

Darin Dimitrov


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:

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);
}
like image 42
Jon Avatar answered Oct 05 '22 23:10

Jon