使用 FileSystemWatcher 从文件中获取新行
我正在观看一个包含以下代码的文件:
[..]
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\";
watcher.Filter = "t.log";
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.EnableRaisingEvents = true;
private static void watcher_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("Changed!");
}
[..]
这有效。 现在,假设文件 t.log 的内容是:
row 1
row 2
row 3
row 4
当我向文件添加(并保存)几行时,文件变成这样:
row 1
row 2
row 3
row 4
row 5
row 6
如何检索添加的行是“第 5 行”和“第 6 行” “?
请注意,该文件可能非常大,因此不能将其内容保留在内存中并与新版本进行比较。 同样,存储最后读取行的值并从该行开始计数也是不可能的,因为这会迫使我每次都读取整个文件,而且可能存在具有相同值的行。
任何帮助真的很感激。
I'm watching a file with the following code:
[..]
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\";
watcher.Filter = "t.log";
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.EnableRaisingEvents = true;
private static void watcher_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("Changed!");
}
[..]
This works. Now, supposed that the content if file t.log is:
row 1
row 2
row 3
row 4
When I add to the file (and save) a couple of lines and the file becomes this:
row 1
row 2
row 3
row 4
row 5
row 6
How can I retrieve that the added lines are "row 5" and "row 6"?
Mind that the file may be very large, so having its content in memory and making a diff with the new version is not an option. Similarly, storing the value of the last read line and count from that on is not possible too, as it would force me to read the whole file every time, plus there may be lines with the same value.
Any help really appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果它是始终附加的日志,您可以保留文件大小和更改:
If it's a log, always appended, you can keep the file size and on change :
我认为它可以工作的唯一用例是当您仅添加行时。 然后简单地存储行数。
The only usecase I see it can work is when you're only adding lines. Then simply store number of lines.