views:

35

answers:

2

hi 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.Directory.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

A: 

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.

Traveling Tech Guy
how would it be as a list? i dont think iv worked with them before and this will need to be as maintainable as possible.
NightsEVil
You've never worked with arrays?
Traveling Tech Guy
not that i know of (im just learning im actually building my first application as a matter of fact)
NightsEVil
A: 
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.

negative