gpt4 book ai didi

c# - 如何使用 FileSystemWatcher 监视父目录下特定名称的所有文件夹?

转载 作者:行者123 更新时间:2023-12-04 15:17:04 25 4
gpt4 key购买 nike

我的目录结构如下所示,其中可以将 csv 文件添加到任何子目录。 (业务逻辑是订单文件先保存在“Vendor”文件夹下,审核通过后移至“Processed”文件夹。)

我只想监控名为“Processed”的文件夹。例如,如果有文件添加到“已处理”文件夹,我想得到通知并在回调方法中做一些事情。如果文件添加到“供应商”文件夹下,我想忽略它们。我应该如何配置 FileSystemWatcher 来实现这一目标?

enter image description here

这就是我现在得到的。

public static void Watch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = path; //here is the path of the "Order" folder;
watcher.Created += FileSystemWatcher_Created;
watcher.EnableRaisingEvents = true;
}

private static void FileSystemWatcher_Created(object source, FileSystemEventArgs e)
{
//do something when there are new files added to the watched directory
}

最佳答案

FileSystemWatcher 有一个名为 IncludeSubdirectories 的属性,当为 true 时,IncludeSubdirectories 递归遍历整个子树,而不仅仅是直接子目录。

所以一个例子是这样的(修改后的 MSDN 例子):

private static void Watch(string watch_folder)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.IncludeSubdirectories = true;
watcher.Path = watch_folder;
/* 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;

// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);

// 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.
}

private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
}

另见

更新

这是一个关于如何过滤通知以仅对基于@MickyD 评论的 Processed 文件夹使用react的小型控制台示例:

class Program
{
static void Main(string[] args)
{

try
{
string path = Path.Combine(Directory.GetCurrentDirectory(), "Order");
Console.WriteLine(path);
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(path);
fileSystemWatcher.IncludeSubdirectories = true;
fileSystemWatcher.Changed += FileSystemWatcher_Changed;
fileSystemWatcher.EnableRaisingEvents = true;

Process.GetCurrentProcess().WaitForExit();
fileSystemWatcher.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

private static void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
if (e.Name.Contains("Processed"))
Console.WriteLine("Processed folder has changed");
}
}

关于c# - 如何使用 FileSystemWatcher 监视父目录下特定名称的所有文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64147869/

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