如何监视似乎一直打开的日志文件(很像notepad++)



我正试图构建一个小程序来监控我的pfirewall.log,但我似乎无法打开它。我发现了很多(简单的)答案,都有点像

// use FilesystemWatcher
// open FileStream
// read from last position to end
// output new lines

这里的问题是:文件似乎总是被另一个进程打开。我想这就是windows对文件的写入过程,因为它一直在被写入,就像Notepad++向我展示的那样

这意味着,由于某种原因,Notepad++可以做我不能做的事情:尽管文件已经打开,但仍可以读取。

我在构造函数中初始化我的监视器:

public FirewallLogMonitor(string path)
{
if (!File.Exists(path))
throw new FileNotFoundException("Logfile not found");
this.file = path;
this.lastPosition = 0;
this.monitor = new FileSystemWatcher(Path.GetDirectoryName(path), Path.GetFileName(path));
this.monitor.NotifyFilter = NotifyFilters.Size;
}

并尝试读取监视器上的文件。更改事件:

private void LogFileChanged(object sender, FileSystemEventArgs e)
{
using (FileStream stream = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (StreamReader reader = new StreamReader(stream))
{
stream.Seek(this.lastPosition, SeekOrigin.Begin);
var newLines = reader.ReadToEnd();
this.lastPosition = stream.Length;
var filteredLines = filterLines(newLines);
if (filteredLines.Count > 0)
NewLinesAvailable(this, filteredLines);
}
}

它总是在new FileStream(...)上抛出IOException,告诉我该文件已经在使用中。

既然Notepad++做到了,我也必须有办法做到,对吧?

**编辑:**一个按钮可以这样做:

public void StartLogging()
{
this.IsRunning = true;
this.monitor.Changed += LogFileChanged;
this.monitor.EnableRaisingEvents = true;
}

**Edit2:**这不是FileMode、FileAccess和IOException的副本:进程无法访问文件"filename",因为它正被另一个进程使用,因为该进程假定我可以控制写入过程。将尝试其他建议,并报告结果。

如果我理解你的问题,你可以使用记事本++本身和一个插件来监控你需要去:

插件->文档监视器->开始监控

如果你没有这个插件,你可以在这里下载:

http://sourceforge.net/projects/npp-plugins/files/DocMonitor/

最新更新