文件夹事件中的新文件

有人可以帮我理解如何构建一个24/7全天候监听特定文件夹的软件(例如C:\ Actions),每次我在该文件夹中放置一个新文件时,软件需要阅读和处理它。

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

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

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

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

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

直到现在我已经以原始的循环方式使用它,每次60秒(睡眠)我正在检查文件夹中的新文件。 那是无用的,不那么有效。

如果有人能帮我理解如何让它更有效,我会很高兴的。

非常感谢你

了解这个课程http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx ,你准备好了。 它有所需的事件。

使用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路径上不能很好地工作。 此外,如果您将大量文件粘贴到目录中,它将溢出缓冲区 ,您可能无法获取添加到该文件夹​​的每个文件的事件。

看看FileSystemWatcher类:

当目录或目录中的文件发生更改时,侦听文件系统更改通知并引发事件。

已更改在指定路径中的文件或目录更改时发生。

已创建创建指定路径中的文件或目录时发生。