0

In reference to Deleting All Files how can we handle IO.Exceptions to quietly "skip" those files that the delete can't do? Should we use a try/catch or is there something built-in?

Looks like a simple question but I'm actually having trouble finding a solution for it on the net...

Community
  • 1
  • 1
eetawil
  • 1,601
  • 3
  • 15
  • 26
  • The only way you can deal with an exception *is* to catch it. – James Jun 30 '14 at 12:35
  • You can refer to this StackOverFlow post very similar to your problem http://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true – lloydom Jun 30 '14 at 13:13

3 Answers3

1

Of course. To update the code from the original answer by John Hartsock:

public void DeleteDirectoryFolders(DirectoryInfo dirInfo, bool ignoreIfFailed = false){
    foreach (DirectoryInfo dirs in dirInfo.GetDirectories()) 
    {
        try
        {
            dirs.Delete(true); 
        }
        catch (IOException)
        {
            if (!ignoreIfFailed)
            {
                throw;
            }
        }
    } 
}

public void DeleteDirectoryFiles(DirectoryInfo dirInfo, bool ignoreIfFailed = false) {
    foreach(FileInfo files in dirInfo.GetFiles()) 
    { 
        try
        {
            files.Delete(); 
        }
        catch (IOException)
        {
            if (!ignoreIfFailed)
            {
                throw;
            }
        }
    } 
}

public void DeleteDirectoryFilesAndFolders(string dirName, bool ignoreIfFailed = false) {
  DirectoryInfo dir = new DirectoryInfo(dirName); 
  DeleteDirectoryFiles(dir, ignoreIfFailed);
  DeleteDirectoryFolders(dir, ignoreIfFailed);
}

You can call it like this:

DeleteDirectoryFilesAndFolders(folder, true); // ignore on error

DeleteDirectoryFilesAndFolders(folder, false); // throw exception

DeleteDirectoryFilesAndFolders(folder); // throw exception
Community
  • 1
  • 1
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

try:

       public void DeleteDirectoryFiles(DirectoryInfo dirInfo) 
              {
                  foreach(FileInfo files in dirInfo.GetFiles()) 
                      {
                         try
                            {
                            files.Delete(); 
                            }
                         catch(IOException ex)
                            {
                                  // code to handle
                            }
                      }

              }
H. Mahida
  • 2,356
  • 1
  • 12
  • 23
0

The only way to handle an exception quietly would be a try catch with nothing in the catch block.

Be sure to only catch the exception you're expecting though (i.e., catch (IOException)) else you might mask some other problem that you weren't aware of.

Dan Puzey
  • 33,626
  • 4
  • 73
  • 96