Quite frequently I need to create a temporary file, do some processing on it, then delete it. In order to ensure the file gets deleted, I put the file deletion code in a try…finally, which got me thinking about writing a simple class that implements IDisposable to handle this scenario, allowing me to use using. It’s very simple, but here it is anyway.
public class TemporaryFile : IDisposable { public TemporaryFile(string fileName) { this.fileName = fileName; } ~TemporaryFile() { DeleteFile(); } public void Dispose() { DeleteFile(); GC.SuppressFinalize(this); } private string fileName; public string FileName { get { return fileName; } } private void DeleteFile() { if (File.Exists(fileName)) File.Delete(fileName); } }
1 comment:
this is a good idea!
cheers thomas
Post a Comment