使用FileSystemWatcher从文件中获取新行 [英] Getting new lines from a file with FileSystemWatcher

查看:123
本文介绍了使用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的内容是:

 行1 
行2
行3
row 4

当我添加到文件(并保存)几行这个文件就变成这样了:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
行5
行6

如何检索添加的行是第5行和第6行?

请注意,该文件可能非常大,因此将其内容放在内存中并与新版本进行比较一个选项。同样,存储最后一个读取行的值和计数也是不可能的,因为它会迫使我每次读取整个文件,再加上可能有相同值的行。

任何帮助的真正赞赏。

解决方案

如果它是一个日志,文件大小和更改:

  using(FileStream fs = new FileStream(t.log,FileAccess.Read))
{
fsSeek(previousSize,SeekOrigin.Begin);
//读取,显示,...
PreviousSize = fs.Length;
}


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.

解决方案

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;
}

这篇关于使用FileSystemWatcher从文件中获取新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆