Reputation: 1717
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...
Upvotes: 0
Views: 140
Reputation: 157136
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
Upvotes: 1
Reputation: 2366
try:
public void DeleteDirectoryFiles(DirectoryInfo dirInfo)
{
foreach(FileInfo files in dirInfo.GetFiles())
{
try
{
files.Delete();
}
catch(IOException ex)
{
// code to handle
}
}
}
Upvotes: 1
Reputation: 34218
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.
Upvotes: 0