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


当前回答

最简单的方法:

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

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

其他回答

下面的示例显示了如何做到这一点。它首先创建一些目录和文件,然后通过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。

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

你不需要更多

DirectoryInfo.GetFileSystemInfos同时返回文件和目录:-

new DirectoryInfo(targetDir).GetFileSystemInfos().ToList().ForEach(x => x.Delete());

或者如果要递归删除:-

        new DirectoryInfo(targetDir).GetFileSystemInfos().ToList().ForEach(x =>
        {
            if (x is DirectoryInfo di)
                di.Delete(true);
            else
                x.Delete();
        });

我用过

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

删除旧图片,我不需要此文件夹中的任何对象

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

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