06 July 2010

Disposable Temporary File

I have recently had the repeated need to create temp files and then delete them when finished.  Since this last step is one which I invariably forget, below is a class that supports the following usage:

using (var tempFileName = new DisposableTempFile(".xls"))
{
 System.IO.File.Copy(sourceFile, tempFileName, overwrite: true);
 // ...
}



using System;
using File = System.IO.File;
using Path = System.IO.Path;

public class DisposableTempFile : IDisposable
{
public string FileName { get; set; }

#region IDisposable Members

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

#endregion

///
/// Initializes a new instance of the DisposableTempFile class.
///
public DisposableTempFile(string extension)
{
this.FileName = Path.ChangeExtension(Path.GetTempFileName(), extension); ;
}

public static implicit operator String(DisposableTempFile file)
{
return file.FileName;
}
}

No comments: