【发布时间】:2011-10-01 03:33:35
【问题描述】:
我想监控我们 PBX 的日志文件是否有更改。我用FileSystemWatcher做了一个小程序。
现在变得奇怪了:当我启动程序时,FileSystemWatcher 永远不会触发 Changed-Event。尽管日志文件确实发生了变化。但是,当我在 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 服务正在使用日志文件!我可以用记事本打开它。
【问题讨论】:
-
您将 FileSystemWatcher 的“路径”属性设置为什么?
-
如果您向我们展示您使用的代码,这将有助于我们了解您的问题。
-
尝试设置
FileSystemWatcher.NotifyFilter属性:msdn.microsoft.com/en-us/library/system.io.notifyfilters.aspx -
我试过
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size。结果相同:( -
如果文件始终处于打开状态,那么听起来就像大小和 lastwrite 元数据(观察者几乎可以肯定操作)仅在文件句柄关闭时更新。
标签: c# file filesystemwatcher