gpt4 book ai didi

c# - 文件夹事件中的新文件

转载 作者:行者123 更新时间:2023-11-30 13:22:28 24 4
gpt4 key购买 nike

有人可以帮助我了解如何构建一个 24/7 运行的软件来监听特定文件夹(例如 C:\Actions),并且每次我在该文件夹中放置一个新文件时,该软件都需要读取并处理它。

如果文件夹中没有文件,软件不应该只等待下一个文件的到来。

文件(action1.txt)内容示例(1+1)

软件正在处理(1+1),将答案(2)保存到另一个文件夹,并从“C:\Actions\”文件夹中删除文件(action1.txt)。

我知道如何读取文件并处理它..

我很难理解如何仅在文件夹中有新文件时才触发软件,以及如何在不使用太多内存或导致内存泄漏的情况下全天候 24/7 运行软件......

直到现在,我一直以无限循环的原始方式使用它,每 60 秒( sleep )我检查文件夹中的新文件。那太没用了,也不太有效。

如果有人能帮助我了解如何使它更有效,我会很高兴..

非常感谢

最佳答案

使用 FileSystemWatcher

该页面的示例:

    // Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "C:\\Actions";
/* 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);
}

不过,在使用此类时需要注意一些事项。它在网络驱动器/UNC 路径上运行不佳。此外,如果您将大量文件粘贴到该目录,它会溢出 buffer并且您可能不会获得添加到文件夹中的每个文件的事件。

关于c# - 文件夹事件中的新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21934817/

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