Deterministic Finalization and IDisposable Part 4: Useful IDisposable Class 2: AutoDeleteFile

This is part 4 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;
        }
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s