C# FileSystemWatcher:如何仅为目录中的新文件引发事件?
FileSystemWatcher:如何仅为目录中的新文件引发事件 我有一个目录,我的服务可以扫描它。我使用C# FileSystemWatcher:如何仅为目录中的新文件引发事件?,c#,filesystemwatcher,C#,Filesystemwatcher,FileSystemWatcher:如何仅为目录中的新文件引发事件 我有一个目录,我的服务可以扫描它。我使用FileSystemWatcher: 建造商: if(Directory.Exists(_dirPath)) { _fileSystemWatcher = new FileSystemWatcher(_dirPath); } 然后,我订阅目录: public void Subscribe() { try { //if (_fileSystemWat
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
}
根据经验,我注意到编辑文件时引发的事件可能会因编辑文件的应用程序而异 有些应用程序覆盖,有些应用程序追加
我发现,时不时地进行轮询,并保留上一次轮询中已经存在的文件列表,比试图正确处理事件更可靠。您的代码对我来说很有用。它只通知新创建的文件。这就是
创建的
事件应该做的。答案解决了您的问题吗?如果是,不要忘记将其标记为答案。将OnCreated
事件命名为OnChanged
,而FileSystemWatcher
类中有一个名为Changed
的事件,这有点令人困惑<代码>e.更改类型是关键。好东西!是ChangeType==WatcherChangeTypes.Created
当事件已链接到Created
时,需要进行检查吗?OP希望监视目录中新文件的创建。附加和覆盖与文件的更新有关。@RBT-我注意到一些应用程序在修改文件时,会删除原始文件,然后用新内容写入同一文件。对于操作系统来说,这看起来像一个新文件,这将引发新文件event.Ohh。这是一个非常有趣的发现。