关于c#:使用FileWatcher检测文件夹中是否有新文件创建 | 珊瑚贝

Detect if there are new files created in a folder using FileWatcher


我想知道在给定目录中是否创建了新文件。我有下一个代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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 存在一些问题.
  • 你用什么来创建 zip 文件? Tmp 文件通常由 zipper 应用程序在创建 zip 之前创建,如果您的 zip 应用程序创建文件然后重命名它,则不会对 zip 文件执行创建文件,因此您不会收到消息。
  • 我正在使用库 DoNetZip 来创建它
  • 显示创建功能以及通知过滤器!
  • 使用 FileSystemWatcher 监视目录的可能重复项


建议你看看这里。之前已解决此问题。

使用 FileSystemWatcher 监控目录

  • 永远不要只放链接…给出详细的答案,记住链接可能会损坏..
  • 如果之前已解决,则应将问题标记为重复,而不是收到此类答案。


来源:https://www.codenong.com/33653841/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_8868.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?