C#删除一个文件夹以及该文件夹内的所有文件和文件夹

我试图删除一个文件夹和该文件夹内的所有文件和文件夹,我使用下面的代码,我得到的错误Folder is not empty ,有什么build议我可以做什么?

 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方法(string,布尔)

 Directory.Delete(folderPath, true); 

尝试:

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

这将recursion地删除“path”下的所有文件和文件夹,假设您有权这样做。

呃,那么调用Directory.Delete(path, true);

Directory.Delete方法有一个recursion的布尔参数,它应该做你需要的

你应该使用:

 dir.Delete(true); 

recursion删除该文件夹的内容。 请参阅MSDN DirectoryInfo.Delete()重载 。

尝试这个。

 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"); } } } 
 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); } }