Create a temporary file from stream object in c#

29,350

Solution 1

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.

Solution 2

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

Solution 3

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
}

Solution 4

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

Share:
29,350
Yair Nevet
Author by

Yair Nevet

Lead Software Engineer. Has a wealth experience in software architecture and development. Obsessed technology books reader and enjoys from well-done tech blogs. Happy to share from my knowledge and to learn from others knowledge! See more about me: My GitHub account My LinkedIn profile Tip: Don't be too reckless with the Bounty feature of stackoverflow! This is part of my favorite tech stack: .NET / C# ORM Databases: SQL / NoSql XML / XSD JavaScript jQuery angularJS HTML CSS

Updated on July 09, 2022

Comments

  • Yair Nevet
    Yair Nevet almost 2 years

    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

  • Sam
    Sam over 12 years
    +1, could you wrap it in a using block. Certainly the best answer so far.
  • bluedog
    bluedog about 9 years
    This is the way to do it when you need to have a longer lifetime than can be expressed with a using block.