I have a widows service that is using FileSystemWatcher
to monitor an incoming folder, I am dropping files to this folder and moving files to the working folder on the change event.
There is a problem when the copying file takes time that time it gives the exception the below exception. And this is understood clearly because the event is fired before the file is copied completely to the incoming folder.
the process cannot access the file because it is being used by another process
protected override async void OnStart(string[] args)
{
FileWatcher fileWatcher = new FileWatcher(_channel, _cancellationToken);
fileWatcher.Run();
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public void Run()
{
FileSystemWatcher watcher = new FileSystemWatcher
{
Path = incomingFolder,
IncludeSubdirectories = false,
NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName,
EnableRaisingEvents = true,
Filter = MyFileExtension
};
// Add event handlers.
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.EnableRaisingEvents = true;
}
For now, to make it work I have added Thread.Sleep(20000);
at the beginning of the OnChange method, this is not reliable, but this also gives errors sometimes. Is there any proper way to do this?
private void OnChanged(object source, FileSystemEventArgs e)
{
Thread.Sleep(20000);
File.Move(incomingFolder, workingFolder);
}