[英]FileSystemWatcher Fires Event After Second Change, But Not First
[英]FileSystemWatcher fires event without the file name
我有一個寵物項目,正在研究FileSystemWatcher困擾我的地方。
這是初始化代碼:
for (var xx = 0; xx < _roots.Count; xx++)
{
var watcher = new FileSystemWatcher();
var root = _roots[xx];
watcher.Path = root;
// watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.EnableRaisingEvents = true;
_rootWatchers.Add(watcher);
}
假設我們正在監視的根目錄為“ c:\\ root”,並且有一個子目錄“ c:\\ root \\ subdir”,其中包含一個名為“ file1.txt”的文件。
觀察程序已啟動並正在運行,我刪除了“ file1.txt”。 調用處理程序時,檢查FileSystemEventArgs
的值。
我期望e.Name == "file1.txt"
和e.FullPath == "c:\\\\root\\\\subdir\\\\file1.txt
。
實際值為"subdir"
和"c:\\\\root\\\\subdir"
。
我敢肯定,這是我在某個地方的文檔中錯過的簡單事情。
您是正確的,您面臨的問題實際上是忘記設置屬性的問題之一。
如果設置watcher.IncludeSubdirectories = true;
,即使在更深的層次上,您也會收到有關文件刪除的通知。
在默認模式下, FileSystemWatcher
僅記錄對給定目錄的更改。 子目錄被建模為類似於文件的目錄條目,它們中的任何添加/刪除都將直接報告為對子目錄的更改(如果您在OnChanged
處理程序中選中FileSystemEventArgs.ChangeType
屬性,將會看到)。
即使打開子目錄監視,您仍然會收到subdir
目錄的更改事件( FileSystemEventArgs.ChangeType = WatcherChangeTypes.Changed
),因為在刪除其中的文件時也會對其進行修改。 這是文件刪除事件的補充。
我的測試代碼:
static void Main(string[] args)
{
var watcher = new FileSystemWatcher();
watcher.Path = @"C:\test_dir";
// watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
while (true)
{
}
}
private static void OnRenamed(object sender, RenamedEventArgs e)
{
Console.WriteLine($"OnRenamed: {e.FullPath}, {e.OldFullPath}");
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"OnChanged: {e.ChangeType}, {e.Name}[{e.FullPath}]");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.