Temporary file helper class

Occasionally it’s necessary to output data into a temporary file, for example in order to pass data to an external program. I threw together this little helper class to help out in such situations.

public class TemporaryFile : IDisposable
{
    public string FilePath { get; protected set; }

    public TemporaryFile()
    {
        FilePath= Path.GetTempFileName();
    }

    public void Dispose()
    {
        if (File.Exists(FilePath))
            File.Delete(FilePath);
    }
}

Use it like this:

using (var tempInputFile = new TemporaryFile())
{
   // Do stuff with tempInputFile.FilePath here...
}

// Dispose will be called at the end of the using statement and so the file will be deleted.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s