using System; using System.IO; using System.Text; using System.Collections.Generic; namespace AniNIX.Shared { public class FileHandle : IDisposable { //Private variables private StreamReader _fileHandle = null; private String _path = null; private String _directory = null; private String _file = null; /// /// Create an object to bundle my usual file operations. /// public FileHandle(String path) { this._path = path; this._directory = Path.GetDirectoryName(path); this._file = Path.GetFileName(path); this.Reset(); } /// /// Read the next line. /// /// Next line public String NextLine() { return _fileHandle.ReadLine(); } /// /// Get the next new line added to the file. /// /// Next new line public string NextNewLine() { FileSystemWatcher fsw = new FileSystemWatcher(_directory); fsw.Path = _directory; fsw.Filter = _file; fsw.NotifyFilter = NotifyFilters.LastWrite; fsw.WaitForChanged(WatcherChangeTypes.Changed); // Optionally, this could be accomplished with http://stackoverflow.com/questions/452902/how-to-read-a-text-file-reversely-with-iterator-in-c-sharp // Instead, we are using a syscall for sake of codespace and testing. return ExecuteCommand.Run(String.Format("tail -n 1 {0}",this._path)); } /// /// Read all contents of the file. /// /// File contents public String ReadAll() { return _fileHandle.ReadToEnd(); } /// /// Close the old handle, if applicable, and open new one. /// public void Reset() { if (this._fileHandle != null) { this._fileHandle.Close(); this._fileHandle.Dispose(); } this._fileHandle = new StreamReader(_path); } /* 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 /// ~FileHandle() { Dispose(false); ReportMessage.Log(Verbosity.Error,"Programmer forgot to dispose of FileHandle. 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; _file = null; _directory = null; } if ( _fileHandle != null) { _fileHandle.Close(); _fileHandle.Dispose(); } } this._isDisposed = true; } } }