0

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);
}
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
  • It's been a while, but don't you get two events on a file creation? I never looked at it carefully, but perhaps the first is "started" and the second is "finished". – Flydog57 Sep 18 '22 at 04:36
  • @Flydog57 no such methods :( my bad I mentioned FileWatcher by mistake, its FileSystemWatcher – Vivek Nuna Sep 18 '22 at 04:45
  • You could periodically check if the file handle is still open https://stackoverflow.com/a/47510579/14868997 – Charlieface Sep 18 '22 at 05:01

0 Answers0