C# FileSystemWatcher有一种奇怪的行为
我想监视PBX的日志文件以了解更改。我制作了一个小程序,用C# FileSystemWatcher有一种奇怪的行为,c#,file,filesystemwatcher,C#,File,Filesystemwatcher,我想监视PBX的日志文件以了解更改。我制作了一个小程序,用FileSystemWatcher实现了这一点 现在有点奇怪了:FileSystemWatcher在我启动程序时从不触发Changed-事件。尽管日志文件确实发生了变化。但是,当我在Windows资源管理器中打开日志文件所在的目录时,程序按预期工作。但只要浏览器窗口保持打开状态。。。怎么回事 操作系统:Windows Server 2008 R2 编辑:对不起,这是代码: class Program { static void M
FileSystemWatcher
实现了这一点
现在有点奇怪了:FileSystemWatcher
在我启动程序时从不触发Changed
-事件。尽管日志文件确实发生了变化。但是,当我在Windows资源管理器中打开日志文件所在的目录时,程序按预期工作。但只要浏览器窗口保持打开状态。。。怎么回事
操作系统:Windows Server 2008 R2
编辑:对不起,这是代码:
class Program
{
static void Main(string[] args)
{
new LogFileWatcher(@"C:\PBX\Dial.log");
System.Console.Read();
}
}
public class LogFileWatcher
{
public string LogFilePath { get; private set; }
private DateTime _lastLogFileWriteTime;
public LogFileWatcher(string path)
{
LogFilePath = path;
var directoryName = Path.GetDirectoryName(LogFilePath);
var fileName = Path.GetFileName(LogFilePath);
var fsw = new FileSystemWatcher { Path = directoryName, Filter = fileName };
fsw.Changed += fsw_Changed;
fsw.EnableRaisingEvents = true;
}
private void fsw_Changed(object sender, FileSystemEventArgs e)
{
// Get and fix the last write time of the log file
var fixLastWriteTime = File.GetLastWriteTime(LogFilePath);
// Don't do anything when file didn't change since last time
if (fixLastWriteTime == _lastLogFileWriteTime) return;
Console.WriteLine("File changed on: {0} - ID:{1}", DateTime.Now.ToLongTimeString(), Guid.NewGuid());
// Save last write time of the log file
_lastLogFileWriteTime = fixLastWriteTime;
}
}
EDIT2:可能这很重要:PBX Windows服务正在使用日志文件!不过我可以用记事本打开它。阅读说明。也许你的情况也一样。关闭文件句柄之前,不会激发FW Changed事件。因此,在WindowsService关闭该文件之前,您几乎被卡住了。出于优化原因,FileStream.Flush()方法不再刷新元数据(Vista和更高版本的Microsoft操作系统)。因此,FileSystemWatcher不会收到任何文件通知,也不会触发已更改的方法
您将FileSystemWatcher的“Path”属性设置为什么?如果您向我们展示您使用的代码,这将有助于我们了解您的问题。请尝试设置
FileSystemWatcher.NotifyFilter
属性:我尝试了NotifyFilter=NotifyFilters.LastWrite | NotifyFilters.Size
。同样的结果:(如果文件总是打开的,那么听起来好像大小和lastwrite元数据(watcher几乎肯定是通过它操作的)只有在文件句柄关闭时才会更新。也许……但是解决方法对我不起作用,因为我无法使用日志上的文件句柄更改Windows服务