C#持续观察正在重建的文件
作者:互联网
我正在尝试连续观看正在删除的日志文件,并在每次更新时重写.
我目前的方法是使用FileSystemWatcher.这在修改文件时效果很好,但是如果我删除文件并创建一个具有相同名称的新文件,它将停止跟踪它.
我目前的做法:
namespace LogReader
{
class Program
{
static void Main(string[] args)
{
Watch();
while (true)
{
}
}
public static void Watch()
{
var watch = new FileSystemWatcher();
watch.Path = @"C:\TEMP\test";
watch.Filter = "test.txt";
watch.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite;
watch.Changed += new FileSystemEventHandler(OnChanged);
watch.EnableRaisingEvents = true;
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
if (e.FullPath == @"C:\TEMP\test\test.txt")
{
Console.Clear();
Stream stream = File.Open(@"C:\TEMP\test\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader streamReader = new StreamReader(stream);
var lines = streamReader.ReadToEnd();
Console.Out.WriteLine(lines);
streamReader.Close();
stream.Close();
}
}
}
}
解决方法:
这是因为Create和Delete操作不会触发FileSystemWatcher的OnChanged事件.所以你需要注册那些事件并分配相同的事件处理程序OnChanged它将如下所示:
watch.Created += new FileSystemEventHandler(OnChanged);
watch.Deleted += new FileSystemEventHandler(OnChanged);
您可以查看This有关FileSystemWatcher的更多信息.
标签:c,file,filesystemwatcher 来源: https://codeday.me/bug/20190608/1199920.html