Reputation: 2564
I want to delete a folder (containing files and sub folder) and It's Sub Folder containing many files and many Sub Folder and So on.. I Googled it but can't get success. Here is my Code.
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
}
}
Problem Is only Main Folder are left undeleted.
Upvotes: 1
Views: 252
Reputation: 56
You should use the DirectoryInfo delete method with the Boolean argument of true to recursively delete. Call this once on the parent/target folder.
DirectoryInfo dir = new DirectoryInfo(TargetFolder);
dir.Delete(true);
Upvotes: 1