Search code examples
c#linqfilesystemwatcher

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


I am currently trying to keep a counter on c# on a local file folder for new files that are created.

I have two sub directories to CD and LP that I have to keep checking.

File System Watcher is only keeping track of my copied folders. Basically I need to keep track of folders created starting with EM* but my code shows the counter increasing when I copy and paste folders and not when I create the EM* folders. e.g EM1 EM2 only EM2-copy increases the counter and even then sometimes it increases +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;
        }

Solution

  • Your code is right, try to create directory with console and MKDIR, it will work. If you create a directory from Explorer its first created as "New folder" and then renamed.

    From Microsoft web: copy and paste is interpreteds as rename 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

    From the same docu, events can raise multipletimes:

    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.