FileSystemWatcher Error Reading Directory

Kmcnet 786 Reputation points
2022-10-24T13:36:10.34+00:00

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;  
  
            GC.KeepAlive(fileSystemWatcher);  
  
            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,152 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 116.6K Reputation points
    2022-10-24T15:00:27.707+00:00

    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
    2023-03-16T12:02:24.22+00:00

    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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.