using System; using System.IO; // file readers and writers using System.Windows.Forms; // Application object using System.Reflection; namespace Standard { public sealed class LogFile : IDisposable { private static int maxsize = 30000; // new file if old one exceeds maxsize private static string fileSuffix = "_log.txt"; // log file suffix private static string fileSpecification; // log file full path and spec private static StreamWriter filewriter; // log file stream writer private static LogFile instance = null; // reference to this class private LogFile() { } // end constructor #region methods of IDisposable ~LogFile() { Dispose(false); } // clean up any resources being used. private void Dispose(bool disposing) { if (disposing) { GC.SuppressFinalize(this); } if (instance != null) { if (filewriter != null) { filewriter.Flush(); filewriter.Close(); filewriter = null; // dereference object } } } public void Dispose() { Dispose(true); } #endregion // user is encouraged to call this public static void Close() { instance.Dispose(); } // main() calls this static method to start the log file; // after that, just call LogFile.WriteLine from anywhere public static void InitLogFile() { if (instance == null) instance = new LogFile(); string stringMe = "LogFile: "; try { if (Application.ProductName.Length==0) { fileSpecification = Application.StartupPath + "\\" + "Test" + fileSuffix; } else { fileSpecification = Application.StartupPath + "\\" + Application.ProductName + fileSuffix; } if (File.Exists(fileSpecification)) // restart file if too big { FileInfo myFileInfo = new FileInfo(fileSpecification); if (myFileInfo.Length > maxsize) File.Delete(fileSpecification); myFileInfo = null; } filewriter = File.AppendText(fileSpecification); // open, or create new // start log with standard info WriteLine("\r\n---------------------------------------------"); string tempString = stringMe + Application.ProductName + " " + Application.ProductVersion + " log opened at " + " " + DateTime.Now + ", username=" + SystemInformation.UserName; WriteLine(tempString); WriteLine(stringMe + ": using"); WriteLine(" " + Application.LocalUserAppDataPath); } catch (Exception ex) { ex.ToString(); } } public static void WriteLine(String myInputLine) { try { if (instance != null) { if (myInputLine.Length!=0) { filewriter.WriteLine(myInputLine); filewriter.Flush(); // update file } } } catch (Exception ex) { ex.ToString(); } } } // end class LogFile() } // end namespace