Published: 2005-02-14
This is part 4/5 of my Deterministic Finalization and IDisposable post series.
I guess my definition of tomorrow is much longer than I thought, but here’s another useful IDisposable class which I shall present without comment: AutoDeleteFile.
using System;
using System.Diagnostics;
using System.IO;
/// <summary>
/// A file wrapper which automatically deletes the file unless Disarm()
/// is called.
/// </summary>
public sealed class AutoDeleteFile : IDisposable
{
private FileInfo m_underlyingFile;
private bool m_armed = true;
private bool m_disposed = false;
public AutoDeleteFile(FileInfo underlyingFile)
{
Debug.Assert(underlyingFile != null);
m_underlyingFile = underlyingFile;
}
~AutoDeleteFile()
{
Dispose(false);
}
public FileInfo File
{
get { return m_underlyingFile; }
}
public void Disarm()
{
m_armed = false;
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
private void Dispose(bool disposing)
{
if (!m_disposed)
{
if (m_armed)
{
try
{
m_underlyingFile.Delete();
}
catch (Exception)
{
// If we can't delete, oh well!
}
}
m_disposed = true;
}
}
}