使用C#,如何删除目录中的所有文件和文件夹,但仍然保留根目录?
当前回答
在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);
}
}
其他回答
string directoryPath = "C:\Temp";
Directory.GetFiles(directoryPath).ToList().ForEach(File.Delete);
Directory.GetDirectories(directoryPath).ToList().ForEach(Directory.Delete);
要删除文件夹,这是使用文本框的代码和使用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);
}
}
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();
});
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.Delete(path,true);
Directory.CreateDirectory(path);
请注意,这可能会删除文件夹上的某些权限。