C#删除该文件夹以及该文件夹中的所有文件和文件夹

Jam*_*mie 88 c# directory

我正在尝试删除文件夹以及该文件夹中的所有文件和文件夹,我正在使用下面的代码,我收到错误Folder is not empty,有关我可以做什么的任何建议?

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);
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*ier 145

dir.Delete(true); // true => recursive delete
Run Code Online (Sandbox Code Playgroud)


Mor*_*dur 90

阅读手册:

Directory.Delete方法(String,Boolean)

Directory.Delete(folderPath, true);
Run Code Online (Sandbox Code Playgroud)

  • 为什么阅读手册时,谷歌更快,最终到这里? (47认同)
  • 这是真的 (4认同)
  • 确实...只是用谷歌搜索,这篇文章是谷歌的第一个结果。 (2认同)
  • 我有时做的是提出问题,然后自己回答,以帮助未来的谷歌员工。StackOverflow 允许您同时发布问题和答案。 (2认同)

jin*_*ngy 22

尝试:

System.IO.Directory.Delete(path,true)
Run Code Online (Sandbox Code Playgroud)

这将递归删除"path"下的所有文件和文件夹,假设您有权这样做.


Yst*_*ter 13

对于那些遇到 DirectoryNotFoundException 的人,请添加此检查:

if (Directory.Exists(path)) Directory.Delete(path, true);
Run Code Online (Sandbox Code Playgroud)


Dmi*_*ruk 6

呃,怎么样只是打电话Directory.Delete(path, true);


Pao*_*sco 5

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