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


当前回答

我用过

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

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

其他回答

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

我用过

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

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

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

如果您知道没有子文件夹,那么像这样的操作可能是最简单的:

    Array.ForEach(Directory.GetFiles(folderName), File.Delete);
using System.IO;

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

foreach (string filePath in filePaths)

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