0

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?

slavoo
  • 5,798
  • 64
  • 37
  • 39
Jeeva
  • 4,585
  • 2
  • 32
  • 56

2 Answers2

1

I guess it's a timing problem. The FileSystemWatcher fires it's Created event immediately when the file was created. This does not mean that all content is written to the file and it is closed again. So it's just accessed by the process who created it because this process has not finished writing to it yet.

TO delete it you have to wait until writing has finished.

PVitt
  • 11,500
  • 5
  • 51
  • 85
0

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);

}
Community
  • 1
  • 1
Surjit Samra
  • 4,614
  • 1
  • 26
  • 36