views:

55

answers:

4

Hello!

Lets say a have some path: C:\Temp\TestFolder1\TestFolder2

And I have some template: C:\Temp

So i want to write function that will delete all subdirectories by template

void DeleteSubdirectories(string tlt, string path) {}

If I call this function with given parameters

DeleteSubdirectories("C:\Temp", "C:\Temp\TestFolder1\TestFolder2");

It must delete TestFolder1\TestFolder2 subdirectories from 'C:\Temp

What is the best way to write this function?

+2  A: 
System.IO.Directory.Delete("Path", true);
Mehdi Golchin
If I call this method like that: Directory.Delete(@"C:\Temp\TestFolder1\TestFolder2", true);It will be delete only **TestFolder2**I don't want to delete all subdirectories from Temp folder and Temp folder itself. I only want to delete folders that are in the Path parameter. In this case: **TestFolder1\TestFolder2**
Alex
@Alex, pardon me, I couldn't realize what you meant. Anyway, if you are after to delete `TestFolder1` from `Temp`, you have to use `System.IO.Directory.Delete(@"C:\Temp\TestFolder1", true);` that deletes the desired directory and its subdirectories as well.
Mehdi Golchin
+1  A: 

Just use Directory.Delete - the overload I linked has a boolean value that indicates if subdirectories should also be deleted.

Oded
A: 

If you desire to delecte "C:\Temp" too, use this:

System.IO.Directory.Delete(@"C:\Temp", true);

If you just want to delete the sub directories use this:

        foreach (var subDir in new DirectoryInfo(@"C:\Temp").GetDirectories()) {
            subDir.Delete(true);
        }

Greets Flo

Florian Reischl
A: 

What you're describing sounds wierd, but try this:

using System;
using System.IO;

static void DeleteSubDirectories(string rootDir, string childPath)
{
    string fullPath = Path.Combine(rootDir, childPath);

    Directory.Delete(fullPath);

    string nextPath = Path.GetDirectoryName(fullPath);

    while (nextPath != rootDir)
    {
        Directory.Delete(nextPath);
        nextPath = Path.GetDirectoryName(nextPath);
    }
}

Use it like:

DeleteSubdirectories("C:\Temp", "TestFolder1\TestFolder2");

Obviously, you'll have to implement the exception handling.

George Howarth