[英]Detect newly created file, just edited file
我正在尝试在编辑或创建发生的那一刻及时读取文件。 还有另一块硬件可以创建文件到我希望访问的文件夹(及时)。
如何使用C#.net检测创建新编辑或创建的文件。 我不想定期轮询该文件夹,因为机器可能在轮询时间间隔之间多次写入。 即我想避免:
这很简单,使用FileSystemWatcher 。
我认为FileSystemWatcher类将为您提供所需的内容。
您可以使用FileSystemWatcher类。 它允许您查看特定目录(您还可以对文件类型应用过滤器),如果文件已更改,则将引发事件。
这里有来自msdn的示例代码:
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = args[1];
/* 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);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
其中OnChanged
和OnRenamed
是具有逻辑的事件处理程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.