FileSystemWatcher Error Reading Directory

Kmcnet 646 Reputation points

Hello everyone and thanks for the help in advance. I am rewriting an old Vb.Net application to use C# .Net 6. The application uses FileSystemWatcher to monitor newly created files in a folder. My code is very basic:

        private static void MonitorDirectory(string path)  
            FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();  
            fileSystemWatcher.Error += OnError;  
            fileSystemWatcher.EnableRaisingEvents = true;  
            fileSystemWatcher.IncludeSubdirectories = true;  
            fileSystemWatcher.Path = path;              
            fileSystemWatcher.Created += FileSystemWatcher_Created;    

However, when I start the application, I receive an error message "Error Reading the Directory". The watcher will sometimes work for a short period of time and then stop listening. However, the older VB.Net version, written in 4.0 monitoring the same folder works perfectly fine. So I think this rules our buffer issues as well as permissions. I'm not sure where to go from here. Any help would be appreciated.

.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,075 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 106.4K Reputation points

    Did you find the line that generates the error?

    Maybe remove the GC.KeepAlive and store the watcher in a static field of the class (instead of local variable).

1 additional answer

Sort by: Most helpful
  1. Abdulkadir Bener 0 Reputation points

    FileSystemWatcher object creation order is important. Give the full path before .EnableRaisingEvents property. I recommend writing the EnableRaisingEvents property as the last option.

            internal static void Set(string Path)
                if (_watcher == null)
                    _watcher = new FileSystemWatcher();
                    _watcher.IncludeSubdirectories = true;
                    _watcher.Path = Path;
                    _watcher.Error += Error;
                    _watcher.Created += Created;
                    _watcher.Changed += Changed;
                    _watcher.Renamed += Renamed;
                    _watcher.Deleted += Deleted;
                    _watcher.EnableRaisingEvents = true;
    0 comments No comments