我想要删除一个文件夹(包含文件和子文件夹)和它的子文件夹包含许多文件和许多子文件夹等等。我用Google搜索但无法获得成功。这是我的代码。
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
}
}
问题只有主文件夹未被删除。
答案 0 :(得分:1)
您应该使用带有布尔参数true的DirectoryInfo delete方法来递归删除。在父/目标文件夹上调用一次。
DirectoryInfo dir = new DirectoryInfo(TargetFolder);
dir.Delete(true);