【发布时间】:2022-01-01 03:47:11
【问题描述】:
我的目标是从 txt 文件中读取最后插入的行,并在控制台中仅显示新插入的行。这是我的代码-
class Program
{
static void Main(string[] args)
{
string path = @"D:\tmp";
MonitorFile(path);
Console.ReadKey();
}
private static void MonitorFile(string path)
{
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
fileSystemWatcher.Path = path;
fileSystemWatcher.Filter = "file.txt";
fileSystemWatcher.Changed += FileSystemWatcher_Changed;
fileSystemWatcher.EnableRaisingEvents = true;
}
private static void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine(""); //From here new inserted lines should be showed on the console.
}
}
我的目标是每次在文本文件的最后添加新行,并且只有插入的新行才会在控制台中一个接一个地出现。在这里,我使用 FileSystemWatcher 来识别 txt 文件中的更改,但似乎无法从 FileSystemWatcher 读取插入的数据。任何帮助都会非常显着。
【问题讨论】:
-
也许:当事件被触发时,以字节为单位存储文件的大小。下次触发时,文件的新大小减去旧大小就是添加/删除的字节数。
-
感谢您的回复。但我需要阅读最后添加到文本文件中的文本。