本文介绍了为什么在Windows 7检测FileSystemWatcher的属性变化,但不能在Windows 8?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用FileSystemWatcher的监控我的应用程序之外的文件更改一些code。

I have some code that uses FileSystemWatcher to monitor file changes outside of my application.

在Windows 7中,使用.NET 4中,低于code会发现当一个文件被编辑和保存在记事本等应用程序,而我的应用程序正在运行。然而,这种逻辑是行不通的使用.NET 4.0在Windows 8特别是,FileSystemWatcher的的Changed事件永远不会触发。

On Windows 7, using .NET 4, the below code would detect when a file had been edited and saved in an application like Notepad, while my app was running. However, this logic isn't working using .NET 4 on Windows 8. Specifically, the FileSystemWatcher's Changed event never fires.

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!");
    }
}

我知道我可以改变NotifyFilter也包括NotifyFilters.LastWrite,它可以解决我的问题。不过,我想了解的为什么code工作在Windows 7中,但现在没有火Changed事件在Windows 8 。我也很想知道,如果有一种方法在Windows 8中运行时,恢复我的Windows 7 FileSystemWatcher的行为(不改变NotifyFilter)。

I understand that I can alter the NotifyFilter to also include NotifyFilters.LastWrite, which can solve my problem. However, I want to understand why this code worked on Windows 7 but now fails to fire the Changed event on Windows 8. I'm also curious to know if there's a way to restore my Windows 7 FileSystemWatcher behavior when running in Windows 8 (without changing the NotifyFilter).

推荐答案

在检查该文件的存档位/编辑后。您的code仅搜索属性的变化,所以我的猜测是,Windows 7正在更新的文件存档位,和Windows 8是没有的。

Check the archive bit on the file before/after you edit it. Your code is only searching for Attributes changes, so my guess is that Windows 7 is updating the Archive bit on the file, and windows 8 is not.

这篇关于为什么在Windows 7检测FileSystemWatcher的属性变化,但不能在Windows 8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 22:23