C# 文件系统观察程序仅记录复制文件的计数

标签 c# linq filesystemwatcher

我目前正在尝试在本地文件夹上的 C# 上保留创建的新文件的计数器。

我有两个 CD 和 LP 子目录,我必须不断检查。

文件系统观察器仅跟踪我复制的文件夹。 基本上我需要跟踪以 EM* 开头创建的文件夹,但我的代码显示当我复制和粘贴文件夹时计数器增加,而不是当我创建 EM* 文件夹时计数器增加。 例如 EM1 EM2 仅 EM2 复制会增加计数器,即使有时它也会增加 +2

        static int LPcounter { get; set; }
        static int CDcounter { get; set; }
        static int LPCreated;
        static int CDCreated;
        FileSystemWatcher CDdirWatcher = new FileSystemWatcher();
        FileSystemWatcher LPdirWatcher = new FileSystemWatcher();

        public Form1()
        {
            InitializeComponent();

            while (true) 
                watch();
        }

        public void watch()
        { 

            CDdirWatcher.Path = @"C:\Data\LotData\CD";
            CDdirWatcher.Filter = "EM*";
            CDdirWatcher.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.LastWrite;
            CDdirWatcher.EnableRaisingEvents = true;
            CDdirWatcher.Created += CDdirWatcher_Created; 


            LPdirWatcher.Path = @"C:\Data\LotData\LP";
            LPdirWatcher.Filter = "EM*";
            LPdirWatcher.NotifyFilter = NotifyFilters.DirectoryName;
            LPdirWatcher.EnableRaisingEvents = true;
            LPdirWatcher.Created += LPdirWatcher_Created;

        } 
        private static void CDdirWatcher_Created(object sender, FileSystemEventArgs e)
        {
            CDCreated += 1;
        }
        private static void LPdirWatcher_Created(object sender, FileSystemEventArgs e)
        {
            LPCreated += 1;
        }

最佳答案

您的代码是正确的,尝试使用控制台和 MKDIR 创建目录,它会起作用。如果您从资源管理器创建目录,则首先将其创建为“新文件夹”,然后重命名。

来自 Microsoft 网站:复制和粘贴被解释为重命名 https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher.notifyfilter?view=netframework-4.8

The operating system and FileSystemWatcher object interpret a cut-and-paste action or a move action as a rename action for a folder and its contents

在同一个文档中,事件可以多次引发:

Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised.

关于C# 文件系统观察程序仅记录复制文件的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58688736/

相关文章:

C#:删除监视文件夹后 FileSystemWatcher 会发生什么

c# - 有没有办法在 C# 中注释允许的值

c# - C# 中的乘法错误

c# - IEnumerable 到用逗号分隔的字符串?

c# - 在 C# 中枚举对象的属性(字符串)

c# - FileSystemWatcher 未调用更改事件

C# - 依赖注入(inject) - 存储库层 - 调用 select

c# - 在标题中使用 '/' 时如何防止列不显示在 WPF 数据网格中?

linq - 比较 RavenDb 中 Where 子句中同一实体的两个属性

c# - FileSystemWatcher 不报告锁定文件中的更改