我一直在试图理解为什么我的FSW不触发任何事件。我在Application_Start中实例化了我的以下类的新对象,并执行了WatchFile(),但是没有任何反应=(
public class FileWatcherClass
{
private FileSystemWatcher _watcher;
public void WatchFile(string fileName, string directory)
{
// Create a new FileSystemWatcher and set its properties.
using (_watcher = new FileSystemWatcher(directory, "*.xml"))
{
_watcher.NotifyFilter = NotifyFilters.Attributes |
NotifyFilters.CreationTime |
NotifyFilters.FileName |
NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.Size |
NotifyFilters.Security;
// Add event handlers.
_watcher.Changed +=
new FileSystemEventHandler(OnChanged);
// Begin watching.
_watcher.EnableRaisingEvents = true;
}
}
// Define the event handlers.
public void OnChanged(object source, FileSystemEventArgs e) {
do something..
}
}
Run Code Online (Sandbox Code Playgroud)
问题在于您使用以下using语句:
using (_watcher = new FileSystemWatcher(directory, "*.xml"))
Run Code Online (Sandbox Code Playgroud)
当执行到达using块的末尾时,将放置观察程序,这意味着它无法再引发事件。
删除using以解决您的问题:
_watcher = new FileSystemWatcher(directory, "*.xml");
Run Code Online (Sandbox Code Playgroud)
但这引入了另一个问题,那就是永远不要部署观察者。一种办法是实行IDisposable上FileWatcherClass,然后根据需要配置的守望者:
public void Dispose()
{
_watcher?.Dispose(); // if _watcher isn't null, dispose it
}
Run Code Online (Sandbox Code Playgroud)
然后,您就可以在处理完FileWatcherClass实例后对其进行处置。
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |