Of late I have been doing alot of work on NUnit, a popular open source Unit Testing framework.The area in which I have spent the most time is extending the available Assert models to accomplish new things.Today I finished and have sent in to be merged a FileAsserter which will compare, byte by byte, any file with any other file.The work is based on some work started by Darrel Norton which I extended and merged with the NUnit way of coding Asserters.In the process of writing the unit tests to support this functionality I found myself in the need to have external files which could move gracefully along with the test library.Easier said than done.

Fortunately for me I remember reading about a way to handle this some time ago on Scott Hanselman's blog.He was in fact just quoting Patrick Cauldwell.Both of the variations of handling this were good, but not perfectly portable.I realized that this could be encapsulated into a re-usable component which implemented the IDisposable interface.This would allow me to use the using() statement and ensure that files were always cleaned up rather than accidently forgotten when you called only half of the routines presented by Scott or Patrick.So without further ado, here is my TestFile class.

  public class TestFile : IDisposable
  {
    
private bool _disposedValue = false;
    
private string _resourceName;
    
private string _fileName;

    
public TestFile(string fileName, string resourceName)
    {
      _resourceName = resourceName;
      _fileName = fileName;

      Assembly a = Assembly.GetExecutingAssembly();
      
using (Stream s = a.GetManifestResourceStream(_resourceName))
      {
        
if (s == null) throw new Exception("Manifest Resource Stream " + _resourceName + " was not found.");

        
using (StreamReader sr = new StreamReader(s))
        {
          
using (StreamWriter sw = File.CreateText(_fileName))
          {
            sw.Write(sr.ReadToEnd());
            sw.Flush();
          }
        }
      }
    }

    
protected virtual void Dispose(bool disposing)
    {
      
if (!this._disposedValue)
      {
        
if (disposing)
        {
          
if (File.Exists(_fileName))
          {
            
File.Delete(_fileName);
          }
        }
      }
      
this._disposedValue = true;
    }


    #region IDisposable Members

    
public void Dispose()
    {
      
// Do not change this code.Put cleanup code in Dispose(bool disposing) above.
      Dispose(true);
      
GC.SuppressFinalize(this);
    }


    #endregion
  }