开发者

How do i check if multiple folders exist if so delete them on button click?

开发者 https://www.devze.com 2023-01-03 17:46 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消