gpt4 book ai didi

c# - FileSystemWatcher:如何只为目录中的新文件增加事件?

转载 作者:行者123 更新时间:2023-11-30 14:07:27 25 4
gpt4 key购买 nike

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
}

关于c# - FileSystemWatcher:如何只为目录中的新文件增加事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40904735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com