如何删除目录中的所有文件和文件夹?

时间:2023-01-14 23:30:46

Using C#, how can I delete all files and folders from a directory, but still keep the root directory?

使用c#,如何从目录中删除所有文件和文件夹,但仍然保留根目录?

29 个解决方案

#1


599  

System.IO.DirectoryInfo di = new DirectoryInfo("YourPath");

foreach (FileInfo file in di.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
    dir.Delete(true); 
}

If your directory may have many files, EnumerateFiles() is more efficient than GetFiles(), because when you use EnumerateFiles() you can start enumerating it before the whole collection is returned, as opposed to GetFiles() where you need to load the entire collection in memory before begin to enumerate it. See this quote here:

如果您的目录可能有许多文件,那么枚举文件()比GetFiles()更有效,因为当您使用EnumerateFiles()时,您可以在返回整个集合之前开始枚举它,而不是在开始枚举之前需要在内存中加载整个集合的GetFiles()。看到这句话:

Therefore, when you are working with many files and directories, EnumerateFiles() can be more efficient.

因此,当您处理许多文件和目录时,EnumerateFiles()可能更有效。

The same applies to EnumerateDirectories() and GetDirectories(). So the code would be:

这同样适用于enumeratedirectory()和getdirectory()。所以代码是:

foreach (FileInfo file in di.EnumerateFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in di.EnumerateDirectories())
{
    dir.Delete(true); 
}

For the purpose of this question, there is really no reason to use GetFiles() and GetDirectories().

对于这个问题,确实没有理由使用GetFiles()和getdirectory()。

#2


158  

Yes, that's the correct way to do it. If you're looking to give yourself a "Clean" (or, as I'd prefer to call it, "Empty" function), you can create an extension method.

是的,这是正确的方法。如果您想给自己一个“Clean”(或者,我更喜欢称之为“Empty”函数),您可以创建一个扩展方法。

public static void Empty(this System.IO.DirectoryInfo directory)
{
    foreach(System.IO.FileInfo file in directory.GetFiles()) file.Delete();
    foreach(System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
}

This will then allow you to do something like..

这样你就可以做一些像……

System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(@"C:\...");

directory.Empty();

#3


61  

The following code will clear the folder recursively:

下面的代码将递归地清除文件夹:

private void clearFolder(string FolderName)
{
    DirectoryInfo dir = new DirectoryInfo(FolderName);

    foreach(FileInfo fi in dir.GetFiles())
    {
        fi.Delete();
    }

    foreach (DirectoryInfo di in dir.GetDirectories())
    {
        clearFolder(di.FullName);
        di.Delete();
    }
}

#4


36  

We can also show love for LINQ:

我们也可以表达对LINQ的爱:

using System.IO;
using System.Linq;
…
var directory = Directory.GetParent(TestContext.TestDir);

directory.EnumerateFiles()
    .ToList().ForEach(f => f.Delete());

directory.EnumerateDirectories()
    .ToList().ForEach(d => d.Delete(true));

Note that my solution here is not performant, because I am using Get*().ToList().ForEach(...) which generates the same IEnumerable twice. I use an extension method to avoid this issue:

注意,这里的解决方案不是performance,因为我使用的是Get*(). tolist (). foreach(…),它生成相同的IEnumerable两次。我使用扩展方法来避免这个问题:

using System.IO;
using System.Linq;
…
var directory = Directory.GetParent(TestContext.TestDir);

directory.EnumerateFiles()
    .ForEachInEnumerable(f => f.Delete());

directory.EnumerateDirectories()
    .ForEachInEnumerable(d => d.Delete(true));

This is the extension method:

这是扩展方法:

/// <summary>
/// Extensions for <see cref="System.Collections.Generic.IEnumerable"/>.
/// </summary>
public static class IEnumerableOfTExtensions
{
    /// <summary>
    /// Performs the <see cref="System.Action"/>
    /// on each item in the enumerable object.
    /// </summary>
    /// <typeparam name="TEnumerable">The type of the enumerable.</typeparam>
    /// <param name="enumerable">The enumerable.</param>
    /// <param name="action">The action.</param>
    /// <remarks>
    /// “I am philosophically opposed to providing such a method, for two reasons.
    /// …The first reason is that doing so violates the functional programming principles
    /// that all the other sequence operators are based upon. Clearly the sole purpose of a call
    /// to this method is to cause side effects.”
    /// —Eric Lippert, “foreach” vs “ForEach” [http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx]
    /// </remarks>
    public static void ForEachInEnumerable<TEnumerable>(this IEnumerable<TEnumerable> enumerable, Action<TEnumerable> action)
    {
        foreach (var item in enumerable)
        {
            action(item);
        }
    }
}

#5


35  

 new System.IO.DirectoryInfo(@"C:\Temp").Delete(true);

 //Or

 System.IO.Directory.Delete(@"C:\Temp", true);

#6


26  

The simplest way:

最简单的方法:

Directory.Delete(path,true);  
Directory.CreateDirectory(path);

Be aware that this may wipe out some permissions on the folder.

请注意,这可能会清除文件夹中的某些权限。

#7


23  

Based on the hiteshbiblog, you probably should make sure the file is read-write.

基于hiteshbiblog,您可能应该确保文件是读写的。

private void ClearFolder(string FolderName)
{
    DirectoryInfo dir = new DirectoryInfo(FolderName);

    foreach (FileInfo fi in dir.GetFiles())
    {
        fi.IsReadOnly = false;
        fi.Delete();
    }

    foreach (DirectoryInfo di in dir.GetDirectories())
    {
        ClearFolder(di.FullName);
        di.Delete();
    }
}

If you know there are no sub-folders, something like this may be the easiest:

如果你知道没有子文件夹,像这样的东西可能是最简单的:

    Directory.GetFiles(folderName).ForEach(File.Delete)

#8


11  

System.IO.Directory.Delete(installPath, true);
System.IO.Directory.CreateDirectory(installPath);

#9


6  

Every method that I tried, they have failed at some point with System.IO errors. The following method works for sure, even if the folder is empty or not, read-only or not, etc.

我尝试过的每一种方法,都在系统的某个点上失败了。IO错误。下面的方法可以确保工作,即使文件夹是空的或者不是空的,只读的或者不是。

ProcessStartInfo Info = new ProcessStartInfo();  
Info.Arguments = "/C rd /s /q \"C:\\MyFolder"";  
Info.WindowStyle = ProcessWindowStyle.Hidden;  
Info.CreateNoWindow = true;  
Info.FileName = "cmd.exe";  
Process.Start(Info); 

#10


5  

The following code will clean the directory, but leave the root directory there (recursive).

下面的代码将清理目录,但保留根目录(递归的)。

Action<string> DelPath = null;
DelPath = p =>
{
    Directory.EnumerateFiles(p).ToList().ForEach(File.Delete);
    Directory.EnumerateDirectories(p).ToList().ForEach(DelPath);
    Directory.EnumerateDirectories(p).ToList().ForEach(Directory.Delete);
};
DelPath(path);

#11


3  

In Windows 7, if you have just created it manually with Windows Explorer, the directory structure is similar to this one:

在Windows 7中,如果您刚刚使用Windows资源管理器手动创建它,那么目录结构与此类似:

C:
  \AAA
    \BBB
      \CCC
        \DDD

And running the code suggested in the original question to clean the directory C:\AAA, the line di.Delete(true) always fails with IOException "The directory is not empty" when trying to delete BBB. It is probably because of some kind of delays/caching in Windows Explorer.

并且运行原始问题中建议的代码来清除目录C:\AAA,当尝试删除BBB时,行di.Delete(true)总是失败,但IOException“目录不是空的”。这可能是因为Windows资源管理器中存在某种延迟/缓存。

The following code works reliably for me:

以下代码对我工作可靠:

static void Main(string[] args)
{
    DirectoryInfo di = new DirectoryInfo(@"c:\aaa");
    CleanDirectory(di);
}

private static void CleanDirectory(DirectoryInfo di)
{
    if (di == null)
        return;

    foreach (FileSystemInfo fsEntry in di.GetFileSystemInfos())
    {
        CleanDirectory(fsEntry as DirectoryInfo);
        fsEntry.Delete();
    }
    WaitForDirectoryToBecomeEmpty(di);
}

private static void WaitForDirectoryToBecomeEmpty(DirectoryInfo di)
{
    for (int i = 0; i < 5; i++)
    {
        if (di.GetFileSystemInfos().Length == 0)
            return;
        Console.WriteLine(di.FullName + i);
        Thread.Sleep(50 * i);
    }
}

#12


3  

Using just static methods with File and Directory instead of FileInfo and DirectoryInfo will perform faster. (see accepted answer at What is the difference between File and FileInfo in C#?). Answer shown as utility method.

使用带有文件和目录的静态方法而不是FileInfo和DirectoryInfo将执行得更快。(参见c#中文件和文件信息的区别)。答案显示为实用方法。

public static void Empty(string directory)
{
    foreach(string fileToDelete in System.IO.Directory.GetFiles(directory))
    {
        System.IO.File.Delete(fileToDelete);
    }
    foreach(string subDirectoryToDeleteToDelete in System.IO.Directory.GetDirectories(directory))
    {
        System.IO.Directory.Delete(subDirectoryToDeleteToDelete, true);
    }
}

#13


2  

string directoryPath = "C:\Temp";
Directory.GetFiles(directoryPath).ToList().ForEach(File.Delete);
Directory.GetDirectories(directoryPath).ToList().ForEach(Directory.Delete);

#14


2  

This version does not use recursive calls, and solves the readonly problem.

这个版本不使用递归调用,并解决了只读问题。

public static void EmptyDirectory(string directory)
{
    // First delete all the files, making sure they are not readonly
    var stackA = new Stack<DirectoryInfo>();
    stackA.Push(new DirectoryInfo(directory));

    var stackB = new Stack<DirectoryInfo>();
    while (stackA.Any())
    {
        var dir = stackA.Pop();
        foreach (var file in dir.GetFiles())
        {
            file.IsReadOnly = false;
            file.Delete();
        }
        foreach (var subDir in dir.GetDirectories())
        {
            stackA.Push(subDir);
            stackB.Push(subDir);
        }
    }

    // Then delete the sub directories depth first
    while (stackB.Any())
    {
        stackB.Pop().Delete();
    }
}

#15


2  

private void ClearFolder(string FolderName)
{
    DirectoryInfo dir = new DirectoryInfo(FolderName);

    foreach (FileInfo fi in dir.GetFiles())
    {
        fi.IsReadOnly = false;
        fi.Delete();
    }

    foreach (DirectoryInfo di in dir.GetDirectories())
    {
        ClearFolder(di.FullName);
        di.Delete();
    }
}

#16


1  

use DirectoryInfo's GetDirectories method.

使用DirectoryInfo GetDirectories的方法。

foreach (DirectoryInfo subDir in new DirectoryInfo(targetDir).GetDirectories())
                    subDir.Delete(true);

#17


1  

The following example shows how you can do that. It first creates some directories and a file and then removes them via Directory.Delete(topPath, true);:

下面的示例展示了如何做到这一点。它首先创建一些目录和文件,然后通过目录删除它们。删除(topPath,真的),:

    static void Main(string[] args)
    {
        string topPath = @"C:\NewDirectory";
        string subPath = @"C:\NewDirectory\NewSubDirectory";

        try
        {
            Directory.CreateDirectory(subPath);

            using (StreamWriter writer = File.CreateText(subPath + @"\example.txt"))
            {
                writer.WriteLine("content added");
            }

            Directory.Delete(topPath, true);

            bool directoryExists = Directory.Exists(topPath);

            Console.WriteLine("top-level directory exists: " + directoryExists);
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.Message);
        }
    }

It is taken from https://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx.

它取自https://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx。

#18


1  

It's not the best way to deal with the issue above. But it's an alternative one...

这不是处理上述问题的最佳方式。但这是另一种选择……

while (Directory.GetDirectories(dirpath).Length > 0)
 {
       //Delete all files in directory
       while (Directory.GetFiles(Directory.GetDirectories(dirpath)[0]).Length > 0)
       {
            File.Delete(Directory.GetFiles(dirpath)[0]);
       }
       Directory.Delete(Directory.GetDirectories(dirpath)[0]);
 }

#19


1  

Here is the tool I ended with after reading all posts. It does

这是我在阅读完所有文章后使用的工具。它

  • Deletes all that can be deleted
  • 删除所有可以删除的内容
  • Returns false if some files remain in folder
  • 如果某些文件仍在文件夹中,则返回false

It deals with

它处理

  • Readonly files
  • 只读的文件
  • Deletion delay
  • 删除延迟
  • Locked files
  • 锁定文件

It doesn't use Directory.Delete because the process is aborted on exception.

它不使用目录。删除,因为进程在异常情况下被中止。

    /// <summary>
    /// Attempt to empty the folder. Return false if it fails (locked files...).
    /// </summary>
    /// <param name="pathName"></param>
    /// <returns>true on success</returns>
    public static bool EmptyFolder(string pathName)
    {
        bool errors = false;
        DirectoryInfo dir = new DirectoryInfo(pathName);

        foreach (FileInfo fi in dir.EnumerateFiles())
        {
            try
            {
                fi.IsReadOnly = false;
                fi.Delete();

                //Wait for the item to disapear (avoid 'dir not empty' error).
                while (fi.Exists)
                {
                    System.Threading.Thread.Sleep(10);
                    fi.Refresh();
                }
            }
            catch (IOException e)
            {
                Debug.WriteLine(e.Message);
                errors = true;
            }
        }

        foreach (DirectoryInfo di in dir.EnumerateDirectories())
        {
            try
            {
                EmptyFolder(di.FullName);
                di.Delete();

                //Wait for the item to disapear (avoid 'dir not empty' error).
                while (di.Exists)
                {
                    System.Threading.Thread.Sleep(10);
                    di.Refresh();
                }
            }
            catch (IOException e)
            {
                Debug.WriteLine(e.Message);
                errors = true;
            }
        }

        return !errors;
    }

#20


0  

DirectoryInfo Folder = new DirectoryInfo(Server.MapPath(path)); 
if (Folder .Exists)
{
    foreach (FileInfo fl in Folder .GetFiles())
    {
        fl.Delete();
    }

    Folder .Delete();
}

#21


0  

using System;
using System.IO;
namespace DeleteFoldersAndFilesInDirectory
{
     class Program
     {
          public static void DeleteAll(string path)
          {
               string[] directories = Directory.GetDirectories(path);
               string[] files = Directory.GetFiles(path);
               foreach (string x in directories)
                    Directory.Delete(x, true);
               foreach (string x in files)
                    File.Delete(x);
          }
          static void Main()
          {
               Console.WriteLine("Enter The Directory:");
               string directory = Console.ReadLine();
               Console.WriteLine("Deleting all files and directories ...");
               DeleteAll(directory);
               Console.WriteLine("Deleted");
          }
     }
}

#22


0  

this will show how we delete the folder and check for it we use Text box

这将显示如何删除文件夹并检查我们使用的文本框

using System.IO;
namespace delete_the_folder
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Deletebt_Click(object sender, EventArgs e)
    {
        //the  first you should write the folder place
        if (Pathfolder.Text=="")
        {
            MessageBox.Show("ples write the path of the folder");
            Pathfolder.Select();
            //return;
        }

        FileAttributes attr = File.GetAttributes(@Pathfolder.Text);

        if (attr.HasFlag(FileAttributes.Directory))
            MessageBox.Show("Its a directory");
        else
            MessageBox.Show("Its a file");

        string path = Pathfolder.Text;
        FileInfo myfileinf = new FileInfo(path);
        myfileinf.Delete();

    }


}

}

#23


0  

using System.IO;

string[] filePaths = Directory.GetFiles(@"c:\MyDir\");

foreach (string filePath in filePaths)

File.Delete(filePath);

#24


0  

Call from main

主要的电话

static void Main(string[] args)
{ 
   string Filepathe =<Your path>
   DeleteDirectory(System.IO.Directory.GetParent(Filepathe).FullName);              
}

Add this method

添加这个方法

public static void DeleteDirectory(string path)
{
    if (Directory.Exists(path))
    {
        //Delete all files from the Directory
        foreach (string file in Directory.GetFiles(path))
        {
            File.Delete(file);
        }
        //Delete all child Directories
        foreach (string directory in Directory.GetDirectories(path))
        {
             DeleteDirectory(directory);
        }
        //Delete a Directory
        Directory.Delete(path);
    }
 }

#25


0  

 foreach (string file in System.IO.Directory.GetFiles(path))
 {
    System.IO.File.Delete(file);
 }

 foreach (string subDirectory in System.IO.Directory.GetDirectories(path))
 {
     System.IO.Directory.Delete(subDirectory,true); 
 } 

#26


0  

To delete the folder, this is code using Text box and a button using System.IO; :

要删除文件夹,这是使用文本框的代码和使用System.IO的按钮;:

private void Deletebt_Click(object sender, EventArgs e)
{
    System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(@"" + delete.Text);

    foreach (FileInfo file in myDirInfo.GetFiles())
    {
       file.Delete();
    }
    foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
    {
       dir.Delete(true);
    }
}

#27


-2  

private void ClearDirectory(string path)
{
    if (Directory.Exists(path))//if folder exists
    {
        Directory.Delete(path, true);//recursive delete (all subdirs, files)
    }
    Directory.CreateDirectory(path);//creates empty directory
}

#28


-3  

The only thing you should do is to set optional recursive parameter to True.

您应该做的惟一一件事是将可选的递归参数设置为True。

Directory.Delete("C:\MyDummyDirectory", True)

目录中。删除(“C:\ MyDummyDirectory”,真的)

Thanks to .NET. :)

多亏了. net。:)

#29


-4  

IO.Directory.Delete(HttpContext.Current.Server.MapPath(path), True)

You don't need more than that

你不需要更多

#1


599  

System.IO.DirectoryInfo di = new DirectoryInfo("YourPath");

foreach (FileInfo file in di.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
    dir.Delete(true); 
}

If your directory may have many files, EnumerateFiles() is more efficient than GetFiles(), because when you use EnumerateFiles() you can start enumerating it before the whole collection is returned, as opposed to GetFiles() where you need to load the entire collection in memory before begin to enumerate it. See this quote here:

如果您的目录可能有许多文件,那么枚举文件()比GetFiles()更有效,因为当您使用EnumerateFiles()时,您可以在返回整个集合之前开始枚举它,而不是在开始枚举之前需要在内存中加载整个集合的GetFiles()。看到这句话:

Therefore, when you are working with many files and directories, EnumerateFiles() can be more efficient.

因此,当您处理许多文件和目录时,EnumerateFiles()可能更有效。

The same applies to EnumerateDirectories() and GetDirectories(). So the code would be:

这同样适用于enumeratedirectory()和getdirectory()。所以代码是:

foreach (FileInfo file in di.EnumerateFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in di.EnumerateDirectories())
{
    dir.Delete(true); 
}

For the purpose of this question, there is really no reason to use GetFiles() and GetDirectories().

对于这个问题,确实没有理由使用GetFiles()和getdirectory()。

#2


158  

Yes, that's the correct way to do it. If you're looking to give yourself a "Clean" (or, as I'd prefer to call it, "Empty" function), you can create an extension method.

是的,这是正确的方法。如果您想给自己一个“Clean”(或者,我更喜欢称之为“Empty”函数),您可以创建一个扩展方法。

public static void Empty(this System.IO.DirectoryInfo directory)
{
    foreach(System.IO.FileInfo file in directory.GetFiles()) file.Delete();
    foreach(System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
}

This will then allow you to do something like..

这样你就可以做一些像……

System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(@"C:\...");

directory.Empty();

#3


61  

The following code will clear the folder recursively:

下面的代码将递归地清除文件夹:

private void clearFolder(string FolderName)
{
    DirectoryInfo dir = new DirectoryInfo(FolderName);

    foreach(FileInfo fi in dir.GetFiles())
    {
        fi.Delete();
    }

    foreach (DirectoryInfo di in dir.GetDirectories())
    {
        clearFolder(di.FullName);
        di.Delete();
    }
}

#4


36  

We can also show love for LINQ:

我们也可以表达对LINQ的爱:

using System.IO;
using System.Linq;
…
var directory = Directory.GetParent(TestContext.TestDir);

directory.EnumerateFiles()
    .ToList().ForEach(f => f.Delete());

directory.EnumerateDirectories()
    .ToList().ForEach(d => d.Delete(true));

Note that my solution here is not performant, because I am using Get*().ToList().ForEach(...) which generates the same IEnumerable twice. I use an extension method to avoid this issue:

注意,这里的解决方案不是performance,因为我使用的是Get*(). tolist (). foreach(…),它生成相同的IEnumerable两次。我使用扩展方法来避免这个问题:

using System.IO;
using System.Linq;
…
var directory = Directory.GetParent(TestContext.TestDir);

directory.EnumerateFiles()
    .ForEachInEnumerable(f => f.Delete());

directory.EnumerateDirectories()
    .ForEachInEnumerable(d => d.Delete(true));

This is the extension method:

这是扩展方法:

/// <summary>
/// Extensions for <see cref="System.Collections.Generic.IEnumerable"/>.
/// </summary>
public static class IEnumerableOfTExtensions
{
    /// <summary>
    /// Performs the <see cref="System.Action"/>
    /// on each item in the enumerable object.
    /// </summary>
    /// <typeparam name="TEnumerable">The type of the enumerable.</typeparam>
    /// <param name="enumerable">The enumerable.</param>
    /// <param name="action">The action.</param>
    /// <remarks>
    /// “I am philosophically opposed to providing such a method, for two reasons.
    /// …The first reason is that doing so violates the functional programming principles
    /// that all the other sequence operators are based upon. Clearly the sole purpose of a call
    /// to this method is to cause side effects.”
    /// —Eric Lippert, “foreach” vs “ForEach” [http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx]
    /// </remarks>
    public static void ForEachInEnumerable<TEnumerable>(this IEnumerable<TEnumerable> enumerable, Action<TEnumerable> action)
    {
        foreach (var item in enumerable)
        {
            action(item);
        }
    }
}

#5


35  

 new System.IO.DirectoryInfo(@"C:\Temp").Delete(true);

 //Or

 System.IO.Directory.Delete(@"C:\Temp", true);

#6


26  

The simplest way:

最简单的方法:

Directory.Delete(path,true);  
Directory.CreateDirectory(path);

Be aware that this may wipe out some permissions on the folder.

请注意,这可能会清除文件夹中的某些权限。

#7


23  

Based on the hiteshbiblog, you probably should make sure the file is read-write.

基于hiteshbiblog,您可能应该确保文件是读写的。

private void ClearFolder(string FolderName)
{
    DirectoryInfo dir = new DirectoryInfo(FolderName);

    foreach (FileInfo fi in dir.GetFiles())
    {
        fi.IsReadOnly = false;
        fi.Delete();
    }

    foreach (DirectoryInfo di in dir.GetDirectories())
    {
        ClearFolder(di.FullName);
        di.Delete();
    }
}

If you know there are no sub-folders, something like this may be the easiest:

如果你知道没有子文件夹,像这样的东西可能是最简单的:

    Directory.GetFiles(folderName).ForEach(File.Delete)

#8


11  

System.IO.Directory.Delete(installPath, true);
System.IO.Directory.CreateDirectory(installPath);

#9


6  

Every method that I tried, they have failed at some point with System.IO errors. The following method works for sure, even if the folder is empty or not, read-only or not, etc.

我尝试过的每一种方法,都在系统的某个点上失败了。IO错误。下面的方法可以确保工作,即使文件夹是空的或者不是空的,只读的或者不是。

ProcessStartInfo Info = new ProcessStartInfo();  
Info.Arguments = "/C rd /s /q \"C:\\MyFolder"";  
Info.WindowStyle = ProcessWindowStyle.Hidden;  
Info.CreateNoWindow = true;  
Info.FileName = "cmd.exe";  
Process.Start(Info); 

#10


5  

The following code will clean the directory, but leave the root directory there (recursive).

下面的代码将清理目录,但保留根目录(递归的)。

Action<string> DelPath = null;
DelPath = p =>
{
    Directory.EnumerateFiles(p).ToList().ForEach(File.Delete);
    Directory.EnumerateDirectories(p).ToList().ForEach(DelPath);
    Directory.EnumerateDirectories(p).ToList().ForEach(Directory.Delete);
};
DelPath(path);

#11


3  

In Windows 7, if you have just created it manually with Windows Explorer, the directory structure is similar to this one:

在Windows 7中,如果您刚刚使用Windows资源管理器手动创建它,那么目录结构与此类似:

C:
  \AAA
    \BBB
      \CCC
        \DDD

And running the code suggested in the original question to clean the directory C:\AAA, the line di.Delete(true) always fails with IOException "The directory is not empty" when trying to delete BBB. It is probably because of some kind of delays/caching in Windows Explorer.

并且运行原始问题中建议的代码来清除目录C:\AAA,当尝试删除BBB时,行di.Delete(true)总是失败,但IOException“目录不是空的”。这可能是因为Windows资源管理器中存在某种延迟/缓存。

The following code works reliably for me:

以下代码对我工作可靠:

static void Main(string[] args)
{
    DirectoryInfo di = new DirectoryInfo(@"c:\aaa");
    CleanDirectory(di);
}

private static void CleanDirectory(DirectoryInfo di)
{
    if (di == null)
        return;

    foreach (FileSystemInfo fsEntry in di.GetFileSystemInfos())
    {
        CleanDirectory(fsEntry as DirectoryInfo);
        fsEntry.Delete();
    }
    WaitForDirectoryToBecomeEmpty(di);
}

private static void WaitForDirectoryToBecomeEmpty(DirectoryInfo di)
{
    for (int i = 0; i < 5; i++)
    {
        if (di.GetFileSystemInfos().Length == 0)
            return;
        Console.WriteLine(di.FullName + i);
        Thread.Sleep(50 * i);
    }
}

#12


3  

Using just static methods with File and Directory instead of FileInfo and DirectoryInfo will perform faster. (see accepted answer at What is the difference between File and FileInfo in C#?). Answer shown as utility method.

使用带有文件和目录的静态方法而不是FileInfo和DirectoryInfo将执行得更快。(参见c#中文件和文件信息的区别)。答案显示为实用方法。

public static void Empty(string directory)
{
    foreach(string fileToDelete in System.IO.Directory.GetFiles(directory))
    {
        System.IO.File.Delete(fileToDelete);
    }
    foreach(string subDirectoryToDeleteToDelete in System.IO.Directory.GetDirectories(directory))
    {
        System.IO.Directory.Delete(subDirectoryToDeleteToDelete, true);
    }
}

#13


2  

string directoryPath = "C:\Temp";
Directory.GetFiles(directoryPath).ToList().ForEach(File.Delete);
Directory.GetDirectories(directoryPath).ToList().ForEach(Directory.Delete);

#14


2  

This version does not use recursive calls, and solves the readonly problem.

这个版本不使用递归调用,并解决了只读问题。

public static void EmptyDirectory(string directory)
{
    // First delete all the files, making sure they are not readonly
    var stackA = new Stack<DirectoryInfo>();
    stackA.Push(new DirectoryInfo(directory));

    var stackB = new Stack<DirectoryInfo>();
    while (stackA.Any())
    {
        var dir = stackA.Pop();
        foreach (var file in dir.GetFiles())
        {
            file.IsReadOnly = false;
            file.Delete();
        }
        foreach (var subDir in dir.GetDirectories())
        {
            stackA.Push(subDir);
            stackB.Push(subDir);
        }
    }

    // Then delete the sub directories depth first
    while (stackB.Any())
    {
        stackB.Pop().Delete();
    }
}

#15


2  

private void ClearFolder(string FolderName)
{
    DirectoryInfo dir = new DirectoryInfo(FolderName);

    foreach (FileInfo fi in dir.GetFiles())
    {
        fi.IsReadOnly = false;
        fi.Delete();
    }

    foreach (DirectoryInfo di in dir.GetDirectories())
    {
        ClearFolder(di.FullName);
        di.Delete();
    }
}

#16


1  

use DirectoryInfo's GetDirectories method.

使用DirectoryInfo GetDirectories的方法。

foreach (DirectoryInfo subDir in new DirectoryInfo(targetDir).GetDirectories())
                    subDir.Delete(true);

#17


1  

The following example shows how you can do that. It first creates some directories and a file and then removes them via Directory.Delete(topPath, true);:

下面的示例展示了如何做到这一点。它首先创建一些目录和文件,然后通过目录删除它们。删除(topPath,真的),:

    static void Main(string[] args)
    {
        string topPath = @"C:\NewDirectory";
        string subPath = @"C:\NewDirectory\NewSubDirectory";

        try
        {
            Directory.CreateDirectory(subPath);

            using (StreamWriter writer = File.CreateText(subPath + @"\example.txt"))
            {
                writer.WriteLine("content added");
            }

            Directory.Delete(topPath, true);

            bool directoryExists = Directory.Exists(topPath);

            Console.WriteLine("top-level directory exists: " + directoryExists);
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.Message);
        }
    }

It is taken from https://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx.

它取自https://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx。

#18


1  

It's not the best way to deal with the issue above. But it's an alternative one...

这不是处理上述问题的最佳方式。但这是另一种选择……

while (Directory.GetDirectories(dirpath).Length > 0)
 {
       //Delete all files in directory
       while (Directory.GetFiles(Directory.GetDirectories(dirpath)[0]).Length > 0)
       {
            File.Delete(Directory.GetFiles(dirpath)[0]);
       }
       Directory.Delete(Directory.GetDirectories(dirpath)[0]);
 }

#19


1  

Here is the tool I ended with after reading all posts. It does

这是我在阅读完所有文章后使用的工具。它

  • Deletes all that can be deleted
  • 删除所有可以删除的内容
  • Returns false if some files remain in folder
  • 如果某些文件仍在文件夹中,则返回false

It deals with

它处理

  • Readonly files
  • 只读的文件
  • Deletion delay
  • 删除延迟
  • Locked files
  • 锁定文件

It doesn't use Directory.Delete because the process is aborted on exception.

它不使用目录。删除,因为进程在异常情况下被中止。

    /// <summary>
    /// Attempt to empty the folder. Return false if it fails (locked files...).
    /// </summary>
    /// <param name="pathName"></param>
    /// <returns>true on success</returns>
    public static bool EmptyFolder(string pathName)
    {
        bool errors = false;
        DirectoryInfo dir = new DirectoryInfo(pathName);

        foreach (FileInfo fi in dir.EnumerateFiles())
        {
            try
            {
                fi.IsReadOnly = false;
                fi.Delete();

                //Wait for the item to disapear (avoid 'dir not empty' error).
                while (fi.Exists)
                {
                    System.Threading.Thread.Sleep(10);
                    fi.Refresh();
                }
            }
            catch (IOException e)
            {
                Debug.WriteLine(e.Message);
                errors = true;
            }
        }

        foreach (DirectoryInfo di in dir.EnumerateDirectories())
        {
            try
            {
                EmptyFolder(di.FullName);
                di.Delete();

                //Wait for the item to disapear (avoid 'dir not empty' error).
                while (di.Exists)
                {
                    System.Threading.Thread.Sleep(10);
                    di.Refresh();
                }
            }
            catch (IOException e)
            {
                Debug.WriteLine(e.Message);
                errors = true;
            }
        }

        return !errors;
    }

#20


0  

DirectoryInfo Folder = new DirectoryInfo(Server.MapPath(path)); 
if (Folder .Exists)
{
    foreach (FileInfo fl in Folder .GetFiles())
    {
        fl.Delete();
    }

    Folder .Delete();
}

#21


0  

using System;
using System.IO;
namespace DeleteFoldersAndFilesInDirectory
{
     class Program
     {
          public static void DeleteAll(string path)
          {
               string[] directories = Directory.GetDirectories(path);
               string[] files = Directory.GetFiles(path);
               foreach (string x in directories)
                    Directory.Delete(x, true);
               foreach (string x in files)
                    File.Delete(x);
          }
          static void Main()
          {
               Console.WriteLine("Enter The Directory:");
               string directory = Console.ReadLine();
               Console.WriteLine("Deleting all files and directories ...");
               DeleteAll(directory);
               Console.WriteLine("Deleted");
          }
     }
}

#22


0  

this will show how we delete the folder and check for it we use Text box

这将显示如何删除文件夹并检查我们使用的文本框

using System.IO;
namespace delete_the_folder
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Deletebt_Click(object sender, EventArgs e)
    {
        //the  first you should write the folder place
        if (Pathfolder.Text=="")
        {
            MessageBox.Show("ples write the path of the folder");
            Pathfolder.Select();
            //return;
        }

        FileAttributes attr = File.GetAttributes(@Pathfolder.Text);

        if (attr.HasFlag(FileAttributes.Directory))
            MessageBox.Show("Its a directory");
        else
            MessageBox.Show("Its a file");

        string path = Pathfolder.Text;
        FileInfo myfileinf = new FileInfo(path);
        myfileinf.Delete();

    }


}

}

#23


0  

using System.IO;

string[] filePaths = Directory.GetFiles(@"c:\MyDir\");

foreach (string filePath in filePaths)

File.Delete(filePath);

#24


0  

Call from main

主要的电话

static void Main(string[] args)
{ 
   string Filepathe =<Your path>
   DeleteDirectory(System.IO.Directory.GetParent(Filepathe).FullName);              
}

Add this method

添加这个方法

public static void DeleteDirectory(string path)
{
    if (Directory.Exists(path))
    {
        //Delete all files from the Directory
        foreach (string file in Directory.GetFiles(path))
        {
            File.Delete(file);
        }
        //Delete all child Directories
        foreach (string directory in Directory.GetDirectories(path))
        {
             DeleteDirectory(directory);
        }
        //Delete a Directory
        Directory.Delete(path);
    }
 }

#25


0  

 foreach (string file in System.IO.Directory.GetFiles(path))
 {
    System.IO.File.Delete(file);
 }

 foreach (string subDirectory in System.IO.Directory.GetDirectories(path))
 {
     System.IO.Directory.Delete(subDirectory,true); 
 } 

#26


0  

To delete the folder, this is code using Text box and a button using System.IO; :

要删除文件夹,这是使用文本框的代码和使用System.IO的按钮;:

private void Deletebt_Click(object sender, EventArgs e)
{
    System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(@"" + delete.Text);

    foreach (FileInfo file in myDirInfo.GetFiles())
    {
       file.Delete();
    }
    foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
    {
       dir.Delete(true);
    }
}

#27


-2  

private void ClearDirectory(string path)
{
    if (Directory.Exists(path))//if folder exists
    {
        Directory.Delete(path, true);//recursive delete (all subdirs, files)
    }
    Directory.CreateDirectory(path);//creates empty directory
}

#28


-3  

The only thing you should do is to set optional recursive parameter to True.

您应该做的惟一一件事是将可选的递归参数设置为True。

Directory.Delete("C:\MyDummyDirectory", True)

目录中。删除(“C:\ MyDummyDirectory”,真的)

Thanks to .NET. :)

多亏了. net。:)

#29


-4  

IO.Directory.Delete(HttpContext.Current.Server.MapPath(path), True)

You don't need more than that

你不需要更多