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


104

我正在尝试删除一个文件夹以及该文件夹中的所有文件和文件夹,我在使用下面的代码,但出现错误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);
}

Answers:



110

阅读手册:

Directory.Delete方法(字符串,布尔值)

Directory.Delete(folderPath, true);

68
为什么要更快地搜索该手册并在此处找到它,为什么要阅读该手册?
reggaeguitar,2015年

5
这是真的
Corvin

4
确实...只是谷歌搜索,而这篇文章是谷歌的第一个结果。
MasterN8

2
有时我要做的是先提出问题,然后自己回答,以帮助将来的Google员工。StackOverflow允许您同时发布问题和答案。
DharmaTurtle

1
我已经开始以这种方式进行所有本地文档处理。并不是常见问题解答,更像是SO问题。即我该怎么办?或这是什么?
Paul Duer

23

尝试:

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

假定您有权这样做,这将递归删除“路径”下的所有文件和文件夹。





3

试试这个。

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

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

0

试试这个:

foreach (string files in Directory.GetFiles(SourcePath))
{
   FileInfo fileInfo = new FileInfo(files);
   fileInfo.Delete(); //delete the files first. 
}
Directory.Delete(SourcePath);// delete the directory as it is empty now.

尽管此代码可以回答问题,但提供有关如何和/或为什么解决问题的其他上下文将提高​​答案的长期价值。阅读此内容
Shanteshwar Inde

0

对于那些遇到DirectoryNotFoundException的用户,请添加以下检查:

if (Directory.Exists(path)) Directory.Delete(path, true);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.