1

I am trying to program a Windows service that automatically deletes the file from a specific folder. But I encountered an error:

Cannot access the file. The file is currently in use by another process/program.

I tried to do the following, but still get the same error.

string[] files = Directory.GetFiles(@"C:\Users\ASIM\AppData\Local\Temp");

//  string[] directories = Directory.GetDirectories(@"C:\Users\ASIM\AppData\Local\Temp", "p*", SearchOption.TopDirectoryOnly);

if (files != null || files.Length != 0)
{
   
    {
        foreach (string f in files)
        {
            try
            {
                File.Delete(f);
            }
            finally { }
        }
    }
  
}

so how to skip deleting a file if it is in use?

TylerH
  • 20,799
  • 66
  • 75
  • 101
BeardGuy
  • 19
  • 1
  • 2
    Does this answer your question? [Is there a way to check if a file is in use?](https://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use) – Cameron Tinker May 27 '20 at 16:53
  • Wading through the link from @CameronTinker, seems all you should really do is add a `catch` block to your try/finally. Catching the specific exception type (`IOException`?) and moving on seems like your best bet. – Sean Skelly May 27 '20 at 17:01
  • Is the service RUNNING AS user "ASIM" ? Does the service even have rights to delete ASIM's temp files? – Señor CMasMas May 27 '20 at 18:13
  • Yes it does, the files not in use get deleted. it isnt about permissions. – BeardGuy May 27 '20 at 22:49

1 Answers1

2

There is no point checking if the file is deletable before deleting it because there will be a small window of opportunity between your check and the delete, where another process will open the file. The best idea is to try and delete it and handle the exception if it occurrs.

Your try/finally should be try/catch with the appropriate exception:

try
{
   File.Delete(f);
}
catch(IOException ex)
{
   // Probably some logging here 
}
Neil
  • 11,059
  • 3
  • 31
  • 56