Monthly Archives: May 2016

Specifying Extensions for Temporary Files

using System;
using System.IO;

public static class IOExtensions
{
    public static FileInfo GetTemporaryFile(string extension = null)
    {
        string path = Path.GetTempPath();
        FileInfo file;
        do
        {
            string fileName = Path.ChangeExtension(Guid.NewGuid().ToString("N"), extension);
            file = new FileInfo(Path.Combine(path, fileName));
        } while (file.Exists);
        using (file.OpenWrite()) { }
        return file;
    }
}