using System; using System.IO; using System.Text; using System.Linq; using System.Collections.Generic; namespace AniNIX.Shared { public class DirHandle : IDisposable { // Internal representations of the directory. private FileSystemWatcher _dirHandle = new FileSystemWatcher(); private String _path; /// /// Create a new DirHandle /// /// The path to watch /// Optional filter to control files by -- accepts regex public DirHandle(String path, String filter = "*.*") { this._path=path; _dirHandle.Path = path; _dirHandle.NotifyFilter = NotifyFilters.LastWrite; _dirHandle.Filter = filter; _dirHandle.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.Size; _dirHandle.EnableRaisingEvents = false; } /// /// Wait until the directory changes /// public void HoldForChange() { _dirHandle.WaitForChanged(WatcherChangeTypes.Changed); return; } /// /// Get a list of files in the path. /// /// A List of strings public List ListContents() { return new List(Directory.GetFiles(@_path)); } /// /// Get the path of the newest file. /// /// A List of strings public String GetNewest() { try { return this.SortedListOfFiles()[0].FullName.Trim(); } catch (Exception e) { e.ToString(); return null; } } /// /// Get the path of the oldest file /// /// A List of strings public String GetOldest() { try { FileInfo[] files = this.SortedListOfFiles(); return files[files.Length-1].FullName.Trim(); } catch (Exception e) { e.ToString(); return null; } } /// /// Sorts the list of files from newest to oldest. /// /// A List of strings private FileInfo[] SortedListOfFiles() { return (new DirectoryInfo(@_path)).GetFiles().OrderByDescending(p => p.CreationTime).ToArray(); } /* IDisposable */ /// /// Clean up this FileStream, implementing IDisposable /// public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// /// Force the GarbageCollector to Dispose if programmer does not /// ~DirHandle() { Dispose(false); ReportMessage.Log(Verbosity.Error,"Programmer forgot to dispose of DirHandle. Marking for Garbage Collector"); } // This bool indicates whether we have disposed of this Raven public bool _isDisposed = false; /// /// Dispose of this FileHandle's resources responsibly. /// private void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { _path = null; } if ( _dirHandle != null) { _dirHandle.Dispose(); } } this._isDisposed = true; } } }