Search code examples
c#windows-servicesfilesystemwatcher

Deleting file in event raised by Filesystemwatcher


I am monitoroing a folder using FileSystemWatcher and deleting the files created under the folder. But my application is throwing me an exception:

File is being used by another application

ifsXmlFileWatcher.Path = "D:\\";
ifsXmlFileWatcher.IncludeSubdirectories = false;
ifsXmlFileWatcher.EnableRaisingEvents = true;
ifsXmlFileWatcher.Created += new FileSystemEventHandler(IfsFileUpload); 

private void IfsFileUpload(object sender, System.IO.FileSystemEventArgs e)
{
    try
    {            
        {               
            File.Delete(e.FullPath);
        }
    }
    catch (Exception exp)
    {
        MessageBox.Show(exp.Message);
    }
}

What might be the problem?


Solution

  • Problem as you know "File is being used by another application". So it may be your own application using it or some other application in your environment using it. Possible solution can be You can keep trying deleting it certain number of times i try here as 5 times and then give up/write event somewhere or show message. I posted similar answer here where someone needs to make sure file copied is success How to know that File.Copy succeeded?

    private void IfsFileUpload(object sender, System.IO.FileSystemEventArgs e)
    {
      bool done = false;
      string file = e.FullPath;
    
      int i = 0;
    
      while (i < 5)
      {
        try
        {
    
          System.IO.File.Delete(file);
          i = 5;
          done = true;
        }
        catch (Exception exp)
        {
          System.Diagnostics.Trace.WriteLine("File trouble " + exp.Message);
          System.Threading.Thread.Sleep(1000);
          i++;
        }
    
      }
      if (!done)
        MessageBox.Show("Failed to delte file " + file);
    
    }