c# – FileSystemWatcher:如何仅为目录中的新文件引发事件?
发布时间:2020-12-15 23:36:19 所属栏目:百科 来源:网络整理
导读:FileSystemWatcher:如何仅为目录中的新文件引发事件? 我有一个目录,我的服务扫描.我使用FileSystemWatcher: 构造函数: if(Directory.Exists(_dirPath)){ _fileSystemWatcher = new FileSystemWatcher(_dirPath);} 然后,我在目录上订阅: public void Sub
FileSystemWatcher:如何仅为目录中的新文件引发事件?
我有一个目录,我的服务扫描.我使用FileSystemWatcher: 构造函数: if(Directory.Exists(_dirPath)) { _fileSystemWatcher = new FileSystemWatcher(_dirPath); } 然后,我在目录上订阅: public void Subscribe() { try { //if (_fileSystemWatcher != null) //{ // _fileSystemWatcher.Created -= FileSystemWatcher_Created; // _fileSystemWatcher.Dispose(); //} if (Directory.Exists(_dirPath)) { _fileSystemWatcher.EnableRaisingEvents = true; _fileSystemWatcher.Created += FileSystemWatcher_Created; _fileSystemWatcher.Filter = "*.txt"; } } 但是,问题是我想在新文件创建(或复制)时获取事件. 如何仅从新文件中获取事件? 解决方法
通过将NotifyFilter设置为NotifyFilters.FileName | NotifyFilters.CreationTime | NotifyFilters.LastWrite您可以观察是否创建了新文件.
您还需要在发生任何更改后检查引发事件中的e.ChangeType == WatcherChangeTypes.Created. static void Main(string[] args) { FileSystemWatcher watcher = new FileSystemWatcher(); string filePath = @"d:watchDir"; watcher.Path = filePath; watcher.EnableRaisingEvents = true; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime | NotifyFilters.LastWrite; watcher.Filter = "*.*"; watcher.IncludeSubdirectories = true; watcher.Created += new FileSystemEventHandler(OnFileCreated); new System.Threading.AutoResetEvent(false).WaitOne(); } private static void OnFileCreated(object sender,FileSystemEventArgs e) { if (e.ChangeType == WatcherChangeTypes.Created) // some code } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |