为什么在Windows 7而不是Windows 8上检测到FileSystemWatcher属性更改?

Cra*_*aig 36 .net c# windows-8

我有一些代码使用FileSystemWatcher来监视我的应用程序之外的文件更改.

在Windows 7上,使用.NET 4,下面的代码将检测文件何时编辑并保存在记事本等应用程序中,同时我的应用程序正在运行.但是,这种逻辑在Windows 8上使用.NET 4无效.具体来说,FileSystemWatcher的Changed事件永远不会触发.

public static void Main(string[] args)
{
    const string FilePath = @"C:\users\craig\desktop\notes.txt";

    if (File.Exists(FilePath))
    {
        Console.WriteLine("Test file exists.");
    }

    var fsw = new FileSystemWatcher();
    fsw.NotifyFilter = NotifyFilters.Attributes;
    fsw.Path = Path.GetDirectoryName(FilePath);
    fsw.Filter = Path.GetFileName(FilePath);

    fsw.Changed += OnFileChanged;
    fsw.EnableRaisingEvents = true;

    // Block exiting.
    Console.ReadLine();
}

private static void OnFileChanged(object sender, FileSystemEventArgs e)
{
    if (File.Exists(e.FullPath))
    {
        Console.WriteLine("File change reported!");
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以改变NotifyFilter以包含NotifyFilters.LastWrite,它可以解决我的问题.但是,我想了解为什么此代码在Windows 7上有效但现在无法在Windows 8上触发Changed事件.我也很想知道在Windows 8中运行时是否有办法恢复我的Windows 7 FileSystemWatcher行为(不更改NotifyFilter).

Ale*_*icu 0

FileSystemWatcher 是出了名的不可靠。尝试订阅所有事件,看看其他事件是否会发生。您可以尝试的一件事是使用计时器定期检查文件是否发生更改,例如每两秒一次,而不是使用 FileSystemWatcher。

  • 虽然我读过其他人对 FileSystemWatcher 的麻烦,但直到 Windows 8 之前我们都让它完美工作。此外,正如我在问题中指出的那样,我们已经通过更改 NotifyFilter 以包含 LastWrite 找到了解决方法。问题仍然是 Windows 8 上发生了什么变化导致此代码不再起作用。 (3认同)