【发布时间】:2016-02-12 17:43:17
【问题描述】:
我想知道在给定目录中是否创建了新文件。我有下一个代码:
private static void CreateWatcher()
{
//Create a new FileSystemWatcher.
FileSystemWatcher watcher = new FileSystemWatcher();
//Set the filter to all files.
watcher.Filter = "*.*";
//Subscribe to the Created event.
watcher.Created += new FileSystemEventHandler(watcher_FileCreated);
//Set the path
watcher.Path = path;
//Enable the FileSystemWatcher events.
watcher.EnableRaisingEvents = true;
}
private static void watcher_FileCreated(object sender, FileSystemEventArgs e)
{
Console.WriteLine("Nuevo archivo creado -> " + e.Name);
}
public static void Main(string[] args)
{
CreateWatcher();
CreateFiles();
Console.Read();
}
在CreatedFiles() 函数中,我在路径上创建了三个新文件(一个zip 和两个txt)。它检测到两个 txt 文件,但与 zip 文件不同。我该如何解决?
【问题讨论】:
-
我的猜测是,由于
watcher是方法中的局部变量,它会被 GC 处理并停止引发事件。Console.Read也可能会阻止Console.WriteLine。 -
它在我身边工作得很好。你可以分享 CreateFiles 代码吗?也许您正在使用线程或没有写下文件的东西?
-
现在它显示 tmp 文件。为什么要这样做?
-
我已经尝试过您的代码(从外部程序创建文件),它可以与 zip 文件一样与通用文件一起正常工作,因此它可能是由在您的文件中创建文件的代码引起的Watcher 有问题的项目。
标签: c# file directory filesystemwatcher