Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

c# - Why are FileSystemWatcher Attribute changes detected on Windows 7 but not Windows 8?

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

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:userscraigdesktop
otes.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!");
    }
}

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...