C#删除文件 - IOException处理

时间:2014-06-30 12:31:14

标签: c#

参考Deleting All Files我们如何能够安静地处理IO.Exceptions" skip"删除无法执行的那些文件?我们应该使用try / catch还是有内置的东西?

看起来像一个简单的问题,但我实际上无法在网上找到解决方案......

3 个答案:

答案 0 :(得分:1)

当然。要更新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);
}

您可以这样称呼它:

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

DeleteDirectoryFilesAndFolders(folder, false); // throw exception

DeleteDirectoryFilesAndFolders(folder); // throw exception

答案 1 :(得分:1)

尝试:

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

              }

答案 2 :(得分:0)

悄悄处理异常的唯一方法是在try catch块中没有任何内容的catch

请确保只捕获您期望的异常(即catch (IOException)),否则您可能会掩盖其他一些您不知道的问题。