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.