C# Code Snippets

Temporary File C# Class

Markus Loibl

Easily create and dispose of temporary files to use in C#.NET applications.

Platform: .NET Framework 2.0

using System.IO;

public class TempFile : IDisposable
{
    private readonly string _tmpfile;

    public TempFile()
        : this(string.Empty)
    { }

    public TempFile(string extension)
    {
        _tmpfile = Path.GetTempFileName();
        if (!string.IsNullOrEmpty(extension))
        {
            string newTmpFile = _tmpfile + extension;

            // create tmp-File with new extension ...
            File.Create(newTmpFile, 0);
            // delete old tmp-File
            File.Delete(_tmpfile);

            // use new tmp-File
            _tmpfile = newTmpFile;
        }
    }

    public string FullPath
    {
        get { return _tmpfile; }
    }

    void IDisposable.Dispose()
    {
        if (!string.IsNullOrEmpty(_tmpfile) && File.Exists(_tmpfile))
            File.Delete(_tmpfile);
    }
}

//Example Use
using(TempFile tmp = new TempFile(".png"))
{
     string filename = tmp.FullPath;
     // use the file
}

Back to C# Code Snippet List