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


当前回答

我尝试过的每一个方法都会在某个时候失败,并出现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); 

其他回答

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();
        });
 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); 
 } 
DirectoryInfo Folder = new DirectoryInfo(Server.MapPath(path)); 
if (Folder .Exists)
{
    foreach (FileInfo fl in Folder .GetFiles())
    {
        fl.Delete();
    }

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

我用过

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

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