Search code examples
c#streamidisposableusing

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


Solution

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