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).
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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.
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).
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;
}
}