FileSystemWatcher Failing on Non-Network Share

Kmcnet 1,066 Reputation points
2022-09-27T19:10:33.26+00:00

Hello everyone and thanks for the help in advance. I am using FileSystemWatcher in .Net 6 to monitor folders located on a Windows Server 2022. The folders are not network shares and reside on internal hard drives (NVME) within the server. The watcher works fine for a period of time, but then simply seems to stop monitoring the folders raising no events. Once the application is closed and reopened, it being to work normally as expected. Here is my code:

        private void Form1_Load(object sender, EventArgs e)  
        {  
		//  Check if another instance running  
            Process thisProcess = Process.GetCurrentProcess();  
            string processName = thisProcess.ProcessName;  
            if (Process.GetProcessesByName(processName).Length > 1)  
            {  
                Application.Exit();  
            }  
            using (var ctx = new myDbContext())  
            {  
                var watchdogRoot = ctx.tblConfiguration.Where(x => x.SettingName == "WatchdogRoot").FirstOrDefault();  
                watchDogDirectory = watchdogRoot.SettingValue.ToString();  
            }  
  
            MonitorDirectory(watchDogDirectory);  
  
        }  
        private static void MonitorDirectory(string path)  
  
        {  
  
            FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();  
  
            fileSystemWatcher.Path = path;  
  
            fileSystemWatcher.Created += FileSystemWatcher_Created;  
  
            fileSystemWatcher.Renamed += FileSystemWatcher_Renamed;  
  
            fileSystemWatcher.Deleted += FileSystemWatcher_Deleted;  
  
            fileSystemWatcher.EnableRaisingEvents = true;  
  
            fileSystemWatcher.IncludeSubdirectories = true;  
  
        }  
        private static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)  
        {  
            string fileName = e.Name.ToString();  
  
            FileInfo fileInfo = new FileInfo(e.FullPath);  
            DirectoryInfo directoryInfo = fileInfo.Directory;  
  
            string MRNumber = Path.GetFileNameWithoutExtension(e.FullPath);  
  
            fileName = fileName.Replace(directoryInfo.Name, "");  
            fileName = fileName.Replace(@"\", "");  
              
            string category = directoryInfo.Name.ToLower();  
  
            using (var ctx = new myDbContext())  
            {  
                ctx.tblFileLog.Add(new Models.tblFileLog() {   
  
                    FilePath = e.FullPath,  
                    Category = category,  
                    FileName = fileName,  
                    FileExtension = fileInfo.Extension,  
                    Processed = "N",  
                    TimeLogged = DateTime.Now                  
                  
                });  
                  
                ctx.SaveChanges();  
            }  
  
        }  
  
        private static void FileSystemWatcher_Renamed(object sender, FileSystemEventArgs e)  
        {  
  
        }  
  
        private static void FileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)  
        {  
  
        }  
  
    }  
}  

Any help would be appreciated.

Developer technologies .NET Other
Developer technologies C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jack J Jun 25,296 Reputation points
    2022-09-28T07:42:23.577+00:00

    @Kmcnet , Welcome to Microsoft Q&A, based on my research, somebody has ever met the problem. the reason may be that the watcher object will be eligible for garbage collection if we put the object in the method.

    You could try the following code to put your statement out of the method and use GC.KeepAlive(Object) Method to make it ineligible for garbage collection like the following code:

    private static FileSystemWatcher fileSystemWatcher;  
      
      private static void MonitorDirectory(string path)  
          
             {  
          
                  fileSystemWatcher = new FileSystemWatcher();  
                   ...  
                  GC.KeepAlive(fileSystemWatcher;    
      
          
             }  
    

    Hope my answer could help you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    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.