使用 FileSystemWatcher 从文件中获取新行

发布于 2024-07-29 16:54:19 字数 809 浏览 7 评论 0原文

我正在观看一个包含以下代码的文件:

        [..]
        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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烦人精 2024-08-05 16:54:19

如果它是始终附加的日志,您可以保留文件大小和更改:

using (FileStream fs = new FileStream("t.log", FileAccess.Read))
{
  fs.Seek(previousSize, SeekOrigin.Begin);
  //read, display, ...
  previousSize = fs.Length;
}

If it's a log, always appended, you can keep the file size and on change :

using (FileStream fs = new FileStream("t.log", FileAccess.Read))
{
  fs.Seek(previousSize, SeekOrigin.Begin);
  //read, display, ...
  previousSize = fs.Length;
}
飞烟轻若梦 2024-08-05 16:54:19

我认为它可以工作的唯一用例是当您仅添加行时。 然后简单地存储行数。

The only usecase I see it can work is when you're only adding lines. Then simply store number of lines.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文