C# FileWatcher 过滤器

C# FileWatcher filter

我的服务中有一个方法可以查看服务配置文件。它看起来像这样:

private void WatchConfigurationFile()
{
    var fileLocation = Assembly.GetExecutingAssembly().Location;


    watcher.Path = Path.GetDirectoryName(fileLocation);
    watcher.NotifyFilter = NotifyFilters.LastWrite;
    watcher.Filter = fileLocation + ".config";

    watcher.Changed += new FileSystemEventHandler(OnConfigChange);
    watcher.EnableRaisingEvents = true;


    Log.DebugFormat("config location: {0}", watcher.Filter.ToString());

}

日志 returns 我的目标文件的完整文件路径位置,包括它存储的位置: C/Users etc etc

但是,当我更新我的配置文件时,更改并没有显示在我的日志文件中。记录是这样完成的:

private void OnConfigChange(object source, FileSystemEventArgs e)
{
    ConfigurationManager.RefreshSection("appSettings");
    Log.DebugFormat("Updated ConnectionString: {0}", ConfigurationManager.AppSettings["dbConn"]);
}  

但是在我的文件观察器 class 中,如果我将过滤器更改为文件的实际名称,在我的例子中,它是服务 exe 名称,末尾带有“.config”。它工作正常。

为什么一个有效,另一个无效?

您应该对所有配置文件使用 watcher.Filter = "*.config";,或者对特定文件使用 watcher.Filter = "yourFileName.config";。此处无需指定完整路径;

As per MSDN: To watch changes in all files, set the Filter property to an empty string (""). To watch a specific file, set the Filter property to the file name. For example, to watch for changes in the file MyDoc.txt, set the Filter property to "MyDoc.txt". You can also watch for changes in a certain type of file. For example, to watch for changes in any text files, set the Filter property to ".txt". Use of multiple filters such as ".txt|*.doc" is not supported.