C# File System Watchers 只记录复制文件的数量

C# File System Watchers is only keeping count of Copied files

我目前正在尝试在本地文件夹中为创建的新文件保留一个 c# 计数器。

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

文件系统观察器只跟踪我复制的文件夹。 基本上我需要跟踪以 EM* 开头创建的文件夹,但我的代码显示当我复制和粘贴文件夹时计数器增加,而不是当我创建 EM* 文件夹时。 例如 EM1 EM2 只有 EM2-copy 会增加计数器,即使这样有时它也会增加 +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 创建目录,它会起作用。如果您从资源管理器创建一个目录,它首先创建为 "New folder" 然后重命名。

来自 Microsoft 网站:复制和粘贴被解释为重命名 https://docs.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.