删除包含许多子文件夹的文件夹和包含更多子文件夹的子文件夹
本文关键字:文件夹 包含更 包含许 删除 | 更新日期: 2023-09-27 18:00:06
我想删除一个文件夹(包含文件和子文件夹),它的子文件夹包含许多文件和许多子文件夹等等。我在谷歌上搜索了它,但没有成功。这是我的密码。
private void TemporaryFiles_Load(object sender, EventArgs e)
{
bool b = IsAdministrator();
if (b != true)
{
MessageBox.Show("You Should Login as Admininstartor to run this Software at it's fullest.");
}
string TargetFolder = @"C:'Users'user'AppData'Local'Temp";
DeleteFolderAndFile(new DirectoryInfo(TargetFolder));
}
static public void DeleteFolderFile(DirectoryInfo directoryInfo)
{
try
{
foreach (FileInfo file in directoryInfo.GetFiles())
{
try
{
file.Delete();
}
catch
{
//Do Nothing
}
}
foreach (DirectoryInfo Folder in directoryInfo.GetDirectories())
{
try
{
Folder.Delete(true);
}
catch
{
//Do Nothing
}
}
foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
{
try
{
DeleteFolderAndFile(subfolder);
}
catch
{
//Do Nothing
}
}
}
catch
{
//Do Nothing
}
}
问题是只有主文件夹未删除。
您应该使用DirectoryInfo delete方法和布尔参数true来递归删除。在父/目标文件夹上调用此操作一次。
DirectoryInfo dir = new DirectoryInfo(TargetFolder);
dir.Delete(true);