【问题标题】:Detect if there are new files created in a folder using FileWatcher使用 FileWatcher 检测文件夹中是否有新文件
【发布时间】: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


【解决方案1】:

建议你看看这里。之前已经解决了这个问题。

Using FileSystemWatcher to monitor a directory

【讨论】:

  • 永远不要只放链接...给出详细答案,记住链接可能会损坏..
  • 如果之前已解决,则应将问题标记为重复,而不是收到此类答案。
猜你喜欢
  • 1970-01-01
  • 2011-02-12
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2011-03-25
  • 2014-07-11
  • 2011-03-27
  • 2010-11-08
相关资源
最近更新 更多