Home > Software design >  File.Delete is not work all the time - How to fix this issue?
File.Delete is not work all the time - How to fix this issue?

Time:07-27

I have used this code in many projects for cleaning up temp files before closing the application, in my current project I see problems. It is not deleting all the files every time. Approx 20-50 files and sometimes 8-12 are left undeleted. If I run the same code twice, it will delete the rest of the files. The files are not in use and I have full access.

What is going on and how can I fix this issue?

OS: Windows 10, Framework: .NET 4.5

Code:

foreach (string sFile in System.IO.Directory.GetFiles("..\\", "videoBuffer_*.avi"))
{
    System.IO.File.Delete(sFile);
}

CodePudding user response:

The reason that the file isn't being deleted could be because it is in use. Or, that it does not exist at the time of deleting. I'd advice putting some checks in place, so that you can be sure the files are deleted and if they cannot be deleted, you can see why not. Within your loop, you should check if the file exists before deleting it. Also, I'd place the foreach in a while loop.

while(DirectoryContainsFiles)
{
    foreach(var file in Directory)
    {
     if(FileExistsInDirectory)
     {
      try
      {
       Delete(file)
      }
      catch(SomeException e)
      {
       Console.log(e.Message);
      }
     }
    }
}

Bare in mind, if the file does not exist, then an exception will not be thrown.

Equally, a method you could explore could be using a FileSystemWatcher, more info here: https://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?redirectedfrom=MSDN&view=net-6.0

CodePudding user response:

You are not able to delete that file while using it into a foreach loop. If you think about what the foreach command is doing, it will make sense. It is like trying to change a hot light build while turned on. You will get burned! You need to turn off that light bulb before removing it. In the same manner, you need to be done with using these files that you are trying to delete.

  • Related