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

时间:2009-08-17 15:48:19

标签: c# .net

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

30 个答案:

答案 0 :(得分:728)

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

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

如果您的目录可能包含许多文件,EnumerateFiles()GetFiles()更有效,因为当您使用EnumerateFiles()时,您可以在返回整个集合之前开始枚举它,而不是GetFiles()您需要在开始枚举之前将整个集合加载到内存中。请参阅此引文here

  

因此,当您使用许多文件和目录时,EnumerateFiles()可以更有效。

同样适用于EnumerateDirectories()GetDirectories()。所以代码是:

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

出于此问题的目的,我们没有理由使用GetFiles()GetDirectories()

答案 1 :(得分:165)

是的,这是正确的方法。如果你想给自己一个“干净”(或者,我更喜欢称之为“清空”功能),你可以创建一个扩展方法。

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

这将允许你做类似的事情。

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

directory.Empty();

答案 2 :(得分:66)

以下代码将以递归方式清除文件夹:

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

答案 3 :(得分:37)

我们也可以表达对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));

请注意,此处的解决方案效率不高,因为我使用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));

这是扩展方法:

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

答案 4 :(得分:37)

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

 //Or

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

答案 5 :(得分:26)

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

    foreach(FileInfo fi in dir.GetFiles())
    {
        try
        {
            fi.Delete();
        }
        catch(Exception) { } // Ignore all exceptions
    }

    foreach(DirectoryInfo di in dir.GetDirectories())
    {
        ClearFolder(di.FullName);
        try
        {
            di.Delete();
        }
        catch(Exception) { } // Ignore all exceptions
    }
}

如果您知道没有子文件夹,这样的话可能是最简单的:

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

答案 6 :(得分:12)

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

答案 7 :(得分:7)

我尝试过的每一种方法,都在某些方面因System.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); 

答案 8 :(得分:6)

以下代码将清除目录,但保留根目录(递归)。

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

答案 9 :(得分:4)

这是我阅读完所有帖子后结束的工具。 它确实

  • 删除所有可删除的内容
  • 如果某些文件保留在文件夹
  • 中,则返回false

它处理

  • 只读文件
  • 删除延迟
  • 锁定文件

它不使用Directory.Delete,因为该进程在异常时中止。

    /// <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;
    }

答案 10 :(得分:4)

仅使用文件和目录的静态方法而不是FileInfo和DirectoryInfo将更快地执行。 (见What is the difference between File and FileInfo in 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);
    }
}

答案 11 :(得分:3)

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

答案 12 :(得分:3)

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

C:
  \AAA
    \BBB
      \CCC
        \DDD

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

以下代码对我来说可靠:

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

答案 13 :(得分:2)

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

答案 14 :(得分:2)

此版本不使用递归调用,并解决了readonly问题。

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 :(得分:1)

我知道这是一个古老的问题,但这是(也许是新的)正确答案:

new DirectoryInfo(folder).Delete(true);

答案 16 :(得分:1)

这不是处理上述问题的最佳方式。但它是另一种......

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

答案 17 :(得分:1)

以下示例说明了如何执行此操作。它首先创建一些目录和一个文件,然后通过Directory.Delete(topPath, true);删除它们:

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

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

答案 18 :(得分:1)

使用DirectoryInfo的GetDirectories方法。

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

答案 19 :(得分:0)

要删除文件夹,这是使用文本框和按钮using 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);
    }
}

答案 20 :(得分:0)

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

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();

    }


}

}

答案 21 :(得分:0)

using System.IO;

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

foreach (string filePath in filePaths)

File.Delete(filePath);

答案 22 :(得分: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");
          }
     }
}

答案 23 :(得分:0)

从主要电话

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

添加此方法

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

答案 24 :(得分:0)

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

    Folder .Delete();
}

答案 25 :(得分:0)

我用过

Directory.GetFiles(picturePath).ToList().ForEach(File.Delete);

用于删除旧图片,并且此文件夹中不需要任何对象

答案 26 :(得分: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); 
 } 

答案 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)

您唯一应该做的就是将optional recursive parameter设置为True

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

感谢.NET。 :)

答案 29 :(得分:-4)

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

您不需要更多