【发布时间】:2015-03-21 18:40:34
【问题描述】:
我希望我的端点在检测到特定文件夹中的文件被删除时发送一个事件。我能够通过使用实现 IWantToRunWhenBusStartsAndStops 的类来使其工作,该类又设置了 FileSystemWatcher 来监视给定的文件夹。我的问题是,这是使用 nservicebus 解决此问题的最佳方式,还是我遗漏了一些可能会给我带来麻烦的东西?
这是我的代码:
public class FileSystem : IWantToRunWhenBusStartsAndStops
{
private FileSystemWatcher watcher;
public void Start()
{
ConfigFileWatcher();
}
public void Stop()
{
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private void ConfigFileWatcher()
{
watcher = new FileSystemWatcher();
watcher.Path = @"c:\";
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
// Begin watching.
watcher.EnableRaisingEvents = true;
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
// fire off an event here...
}
}
【问题讨论】:
-
您的问题/顾虑到底是什么?
-
我想我只是想知道是否有更好的方法可以做到这一点和/或这种方法是否存在任何性能问题? IWantToRunWhenBusStartsAndStops 接口是否打算这样使用?
-
你测试过它可以工作吗?公车启动后不会被处理掉吗?
-
是的,它确实有效,即使在公共汽车启动后它仍继续有效。我还以为它会被处理掉。这就是为什么我不确定这是否是正确的方法,因为它感觉“错误”:)
标签: c# nservicebus filesystemwatcher