简体   繁体   中英

C# Winforms - Delete Folders on hard drive with specific file names?

I want to be able to pass in the path of a folder to an application and have the program run through the entire contents of that folder, including nested folders and files, deleting any folder that it comes across which has a specific name.

I have looked around for potential ways of doing this however I cannot seem to find any good documentation.

Help would be greatly appreciated.

Kind regards,

Try something like this, which deletes any directory found within the initial directory that matches the name you specify:

  public void RecursiveDelete(string path, string name)
  {
     foreach (string directory in Directory.GetDirectories(path))
     {
        if (directory.EndsWith("\\" + name))
        {
           Directory.Delete(directory, true);
        }
        else
        {
           RecursiveDelete(directory, name);
        }
     }
  }

And then call RecursiveDelete("initial path", "name of directory to delete");

Go recursive.

Basically, have a function that takes a folder name as its argument and have it call Directory.GetDirectories(), iterate through the string[] it returns, calling itself with each new string as a parameter , then calling Directory.GetFiles() or whatever that function was and deleting each. When it returns, delete that folder.

So imagine you have Foo Foo\\a.txt Foo\\b.txt Foo\\Bar Foo\\Bar\\c.txt

Starting at Foo, it'd detect Bar and recurse into it. In Bar, it'd find no folders, so no more recursing from there. Finding c.txt, it is deleted. Returning to Foo, it'd delete Bar, then find a.txt and b.txt, deleting each.

Easy.

Did you check MSDN? The Directory class will be your friend here:

public void DeleteFiles(string path, string toDelete)
    {
        if(Directory.Exists(path))
        {
            foreach(string folder in Directory.GetDirectories(path))
            {
                if(toDelete == Path.GetDirectoryName(folder))
                {
                    DeleteFilesInFolder(folder);
                    Directory.Delete(folder);
                }
            }
        }
    }

You'll have to delete the files in the folder first, but the method is much the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM