FileSystemWatcher并非总是触发

时间:2019-07-26 11:28:46

标签: c# filesystemwatcher

如果我使用notepad.exe更改文件,则FileSystemWatcher可以工作,但是如果我使用VisualStudio更改文件,则不能。为什么? 另请参阅:Powershell File Watcher Not Picking Up File Changes Made in Visual Studio

static void FileWatcher()
{
    FileSystemWatcher watcher = new FileSystemWatcher
    {
        Path = Path.GetDirectoryName(@"D:\Test\"),
        NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size,
        Filter = "file.txt",
        EnableRaisingEvents = true
    };
    watcher.Changed += OnFileChanged;
}

static void OnFileChanged(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("{0}  Watcher:  {1}  {2}", DateTime.Now, e.ChangeType, e.FullPath);
}

PS。 watcher.Renamed有效。谢谢mjwills。

1 个答案:

答案 0 :(得分:1)

通过添加以下代码行,您应该能够捕获所有事件。

watcher.Deleted += OnFileChanged;
watcher.Created += OnFileChanged;