here is my code... no FileSystemWatcher events are ever hit wen creating a new file into the Foo directory. What is wrong with my code?
I am testing this from an NUnit test by calling fileMonitorService.StartMonitoringForNewFiles(new RobotParameters()).
// attribute for autofac IoC
[AutoRegister]
public class FileMonitorService
{
private FileSystemWatcher _fileWatcher = new FileSystemWatcher();
public void StartMonitoringForNewFiles(RobotParameters parameters)
{
_fileWatcher.Path = @"c:\testfiles\foo";
_fileWatcher.NotifyFilter = NotifyFilters.Attributes |
NotifyFilters.CreationTime |
NotifyFilters.FileName |
NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.Size |
NotifyFilters.Security;
_fileWatcher.Filter = "*.xlsx";
_fileWatcher.Created += new FileSystemEventHandler((sender, e) => OnFileCreated(sender, e, parameters));
_fileWatcher.Renamed += new RenamedEventHandler((sender, e) => OnFileRenamed(sender, e, parameters));
_fileWatcher.Error += new ErrorEventHandler(OnError);
_fileWatcher.EnableRaisingEvents = true;
}
public void StopMonitoringForFiles()
{
_fileWatcher.EnableRaisingEvents = false;
}
private void OnFileRenamed(object sender, RenamedEventArgs e, RobotParameters parameters)
{
parameters.FileToProcess = e.FullPath;
parameters.FileCreated = true;
}
private void OnFileCreated(object sender, FileSystemEventArgs e, RobotParameters parameters)
{
parameters.FileToProcess = e.FullPath;
parameters.FileCreated = true;
}
private void OnError(object sender, ErrorEventArgs e)
{
var foo = e.GetException();
}
}
I never could get this to work and based on my google research, many others have had the same problem. I also tried using System.Timers.Timer and it's Elapsed event would not raise either. Google research showed lots of others having this problem too. All my code was in a try/catch and no errors were ever raised by either. I unfortunately had to write my own file monitor code and while it is not pretty, it works. I'm posting it for any others who may have this problem and who may be looking for a custom solution.
public class FileMonitorService
{
private bool stopProcessing = false;
public void StartMonitoringForNewFiles(RobotParameters parameters)
{
try
{
while (stopProcessing == false)
{
stopProcessing = IsFileReady(parameters);
Thread.Sleep(5000); // sleeps for 5 seconds
if (stopProcessing == true)
{
break; // get out of loop since file is ready
}
}
}
catch (Exception e)
{
throw;
}
}
private bool IsFileReady(RobotParameters parameters)
{
try
{
// code to try opening a file goes here
// or code to see if files exist goes here
// assuming file was opened with no errors and is ready for processing
return true;
}
catch (Exception e)
{
// file is not ready for processing
// and could not be opened
return false;
}
}
return false;
}
}