Goober
Goober

Reputation: 13506

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,

Upvotes: 2

Views: 3337

Answers (3)

Stuart Grassie
Stuart Grassie

Reputation: 3073

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.

Upvotes: 0

Kawa
Kawa

Reputation: 1488

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.

Upvotes: 0

Donut
Donut

Reputation: 112825

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");

Upvotes: 6

Related Questions