C#删除一个文件夹,该文件夹中的所有文件和文件夹

问题描述:

我想删除一个文件夹,该文件夹中的所有文件和文件夹,我使用下面的代码,我得到的错误Folder is not empty,什么什么建议我可以?C#删除一个文件夹,该文件夹中的所有文件和文件夹

try 
{ 
    var dir = new DirectoryInfo(@FolderPath); 
    dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; 
    dir.Delete(); 
    dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[i].Index); 
} 
catch (IOException ex) 
{ 
    MessageBox.Show(ex.Message); 
} 

dir.Delete(true); // true => recursive delete 

阅读手册:

Directory.Delete Method (String, Boolean)

Directory.Delete(folderPath, true); 
+14

为什么要阅读手册,当它更快地谷歌它,并最终在这里? – reggaeguitar 2015-01-23 21:08:39

+0

设置为true时,将删除路径中的所有目录,子目录和文件。它是否也会删除路径本身?如果设置为false,它是否会删除路径以及路径中的子目录和文件? – helloworld 2015-05-07 13:54:39

Directory.Delete方法具有递归布尔参数,它应该做的事情,你需要

+0

设置为true时,将删除路径中的所有目录,子目录和文件。它是否也会删除路径本身?如果设置为false,它是否会删除路径以及路径 – helloworld 2015-05-07 13:53:58

犯错,那只是请拨打Directory.Delete(path, true);

+0

中的子目录和文件如果设置为true,则会删除路径中的所有dir,subdir和文件。它是否也会删除路径本身?如果设置为false,它是否会删除路径以及路径中的子目录和文件? – helloworld 2015-05-07 13:53:50

尝试:

System.IO.Directory.Delete(path,true) 

这将递归删除所有文件和文件夹下的“路径”假设你有权限这样做。

+0

设置为true时,将删除路径中的所有目录,子目录和文件。它是否也会删除路径本身?如果设置为false,它是否会删除路径以及路径中的子目录和文件? – helloworld 2015-05-07 13:54:28

你应该使用:

dir.Delete(true); 

用于递归删除该文件夹中的内容了。请参阅MSDN DirectoryInfo.Delete() overloads

+0

设置为true时,将删除路径中的所有dir,subdir和文件。它是否也会删除路径本身?如果设置为false,它是否会删除路径以及路径中的子目录和文件? – helloworld 2015-05-07 13:54:18

public void Empty(System.IO.DirectoryInfo directory) 
{ 
    try 
    { 
     logger.DebugFormat("Empty directory {0}", directory.FullName); 
     foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete(); 
     foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true); 
    } 
    catch (Exception ex) 
    { 
     ex.Data.Add("directory", Convert.ToString(directory.FullName, CultureInfo.InvariantCulture)); 

     throw new Exception(string.Format(CultureInfo.InvariantCulture,"Method:{0}", ex.TargetSite), ex); 
    } 
} 

试试这个。

namespace EraseJunkFiles 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      DirectoryInfo yourRootDir = new DirectoryInfo(@"C:\somedirectory\"); 
      foreach (DirectoryInfo dir in yourRootDir.GetDirectories()) 
        DeleteDirectory(dir.FullName, true); 
     } 
     public static void DeleteDirectory(string directoryName, bool checkDirectiryExist) 
     { 
      if (Directory.Exists(directoryName)) 
       Directory.Delete(directoryName, true); 
      else if (checkDirectiryExist) 
       throw new SystemException("Directory you want to delete is not exist"); 
     } 
    } 
}