I have a few folders created by my application and id like that when they click a button named "clean up" that it would check to see if any of the predetermined folders exist, if they do then delete them, this is what I have tried so far whats wrong with it?
string tempFolder = Environment.GerFolderPath(Environment.SpecialFolder.ApplicationData);
if (Directory.Exists(tempFolder + "//" + "temp1"))
if (Directory.Exists(tempFolder + "//" + "temp2"))
if (Directory.Exists(tempFolder + "//" + "temp3"))
if (Directory.Exists(tempFolder + "//" + "temp4"))
{
System.IO.Directory.Delete(tempFolder + "\\" + "temp1", true);
System.IO.Directo开发者_如何学JAVAry.Delete(tempFolder + "\\" + "temp2", true);
System.IO.Directory.Delete(tempFolder + "\\" + "temp3", true);
System.IO.Directory.Delete(tempFolder + "\\" + "temp4", true);
}
else
{
MessageBox.Show("No Cleanup Needed");
}
So whats wrong? I tested it and it seemed to with 2 folder but not 4 or more
if(statement1)
if(statement2)
if(statement3)
if(statement4)
{
action();
} else
{
anotherAction()
}
Means
if(statement1)
{
if(statement2)
{
if(statement3)
{
if(statement4)
{
action();
}
else
{
anotherAction()
}
}
}
}
So, if one of the statements is false nothing will be executed in this case.
Your if
statements are ordered incorrectly.
Should be:
bool cleanupNeeded = false;
if (Directory.Exists(tempFolder + "//" + "temp1"))
{
System.IO.Directory.Delete(tempFolder + "\\" + "temp1", true);
cleanupNeeded = true;
}
if (Directory.Exists(tempFolder + "//" + "temp2"))
{
System.IO.Directory.Delete(tempFolder + "\\" + "temp2", true);
cleanupNeeded = true;
}
.
.
.
if(!cleanupNeeded)
{
//show your message box
}
Of course, you can hold the names of the directories in an array (or list) and iterate over them with a loop, making the code more readable, maintainable and scalable.
精彩评论