C#:使用FileSystemWatcher监视文件的更改 [英] C#: Using FileSystemWatcher to watch for changes to files
问题描述
好的,所以我从如何检查打开的文件是否已更新我应该使用 FileSystemWatcher 用于监视文件的更改。那么现在问题是我是否必须跟踪许多文件,我是否为每个文件创建了一个观察者?此外,一旦文件关闭,我必须以某种方式处理观察者。是否有字典< string,FileSystemWatcher>
存储文件路径和 FileSystemWatcher
的方法?当我打开更多文件时,我添加更多观察者,当我关闭时,适当地处理观察者。有太多的观察者会不会是一件坏事?
Ok, so I learnt from How to check if a open file has been updated that I should use a FileSystemWatcher to watch for changes to files. Then now, the question is if I must keep track of many files, do I create 1 watcher for each file? Also, I must somehow dispose of the watcher once the file is closed. Is having a Dictionary<string, FileSystemWatcher>
storing the filepath and the FileSystemWatcher
the way to go? as I open more files, I add more watcher and as I close, dispose of the watchers appropriately. Will having too many watchers be a bad thing?
更新
我只是确实
protected void AttachFileMonitor(EditorTabViewModel tab)
{
string file = tab.FilePath;
if (!_fsWatchers.ContainsKey(file))
{
var watcher = new FileSystemWatcher();
watcher.Path = Path.GetDirectoryName(file);
watcher.Filter = Path.GetFileName(file);
watcher.Changed += (s, e) =>
{
string message = "";
string caption = "";
MessageBoxButton buttons = MessageBoxButton.YesNo;
MessageBoxImage image = MessageBoxImage.Question;
MessageBoxResult defaultResult = MessageBoxResult.Yes;
MessageBoxResult result = _dialogSvc.GetMessageBox(message, caption, buttons, image, defaultResult);
if (result == MessageBoxResult.Yes)
{
tab.Open(file);
}
};
_fsWatchers.Add(file, watcher);
}
}
protected void DetachFileMonitor(EditorTabViewModel tab)
{
if (_fsWatchers.ContainsKey(tab.FilePath)) {
_fsWatchers.Remove(tab.FilePath);
}
}
我发现已更改( )
永远不会被触发...
I found that Changed()
never gets triggered ...
推荐答案
如果你为每个目录创建一个观察者就足够了(并且可选地,您可以让观察者监视整个目录树。)然后,您可以使用事件将更改的文件与您感兴趣的文件列表进行比较。
It's enough if you create a watcher for each directory (and optionally, you can have the watcher to monitor a whole directory tree.) You can then use the events to compare the changed files with the list of files you are interested in.
我建议你为观察者制作某种保姆课程,以确保你不会处置活跃的观察者,或创造重复。只是一个提示:)
I would suggest you make some kind of "nanny" class for the watchers to ensure you doesn't dispose active watchers, or create duplicate. Just a tip :)
顺便说一下,是的,有一个限制,你不能创建无限的观察者。在特定的情况下,这可能是一个问题,但很可能,情况并非如此
Btw, yes, there's a limit, you can't create infinite watchers. In specific scenarios that can be a problem, but most likely, that's not the case for you
这篇关于C#:使用FileSystemWatcher监视文件的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!