我的应用程序写入一个日志文件(目前使用的是log4net).我想设置一个计时器和一个后台工作人员来读取日志文件,并在写入时以我的形式将其内容打印成一些控件.
我不能使用FileSystemWatcher类,因为似乎坏了:有时事件“改变”触发,有时不会.它具有极低的“合并利率”.
所以我创建了一个计时器和一个FileSystemWatcher.在定时器的“tick”事件中,后台工作人员完成其工作.
问题是:如何只阅读自上次检查工作人员以来添加的行?
public LogForm() { InitializeComponent(); logWatcherTimer.Start(); } private void logWatcherTimer_Tick(object sender,EventArgs e) { FileInfo log = new FileInfo(@"C:\log.txt"); if(!logWorker.IsBusy) logWorker.RunWorkerAsync(log); } private void logWorker_DoWork(object sender,DoWorkEventArgs e) { // Read only new lines since last check. FileInfo log = (FileInfo) e.Argument; // Here is the main question! }
private void logWatherWorker_DoWork(object sender,DoWorkEventArgs e) { // retval string newLines = string.Empty; FileInfo log = (FileInfo) e.Argument; // Just skip if log file hasn't changed if (lastLogLength == log.Length) return; using (StreamReader stream = new StreamReader(log.FullName)) { // Set the position to the last log size and read // all the content added stream.BaseStream.Position = lastLogLength; newLines = stream.ReadToEnd(); } // Keep track of the previuos log length lastLogLength = log.Length; // Assign the result back to the worker,to be // consumed by the form e.Result = newLines; }
解决方法
每次读取日志时,请检查并存储文件大小,然后在下次阅读时在该位置启动文本阅读器(或任何您正在使用的).