views:

958

answers:

1

I need to delete a Virtual Directory and Application pool from .NET as part of my uninstall method. I found the following code on the web somewhere:

    private static void DeleteTree(string metabasePath)
    {
        // metabasePath is of the form "IIS://<servername>/<path>"
        // for example "IIS://localhost/W3SVC/1/Root/MyVDir" 
        // or "IIS://localhost/W3SVC/AppPools/MyAppPool"
        Console.WriteLine("Deleting {0}:", metabasePath);

        try
        {
            DirectoryEntry tree = new DirectoryEntry(metabasePath);
            tree.DeleteTree();
            tree.CommitChanges();
            Console.WriteLine("Done.");
        }
        catch (DirectoryNotFoundException)
        {
            Console.WriteLine("Not found.");
        }
    }

but it seems to throw a COMException on tree.CommitChanges();. Do I need this line? Is it a correct approach?

+5  A: 

If you're deleting objects such as application pools, virtual directories or IIS applications, you need to do it like this:

string appPoolPath = "IIS://Localhost/W3SVC/AppPools/MyAppPool";
using(DirectoryEntry appPool = new DirectoryEntry(appPoolPath))
{
    using(DirectoryEntry appPools = 
               new DirectoryEntry(@"IIS://Localhost/W3SVC/AppPools"))
    {
        appPools.Children.Remove(appPool);
        appPools.CommitChanges();
    }
}

You create a DirectoryEntry object for the item you want to delete then create a DirectoryEntry for its parent. You then tell the parent to remove that object.

You can also do this as well:

string appPoolPath = "IIS://Localhost/W3SVC/AppPools/MyAppPool";
using(DirectoryEntry appPool = new DirectoryEntry(appPoolPath))
{
    using(DirectoryEntry parent = appPool.Parent)
    {
        parent.Children.Remove(appPool);
        parent.CommitChanges();
    }
}

Depending on the task in hand I'll use either method.

Kev

Kev
is there an easy way to get the parent, when I have the child DirectoryEntry? appPool.Parent would work?
Grzenio
appPool.Parent will work fine.
Kev
minor casing issue with "appPoolpath" vrs "appPoolPath".other than that great answer
Simon
@simon - well spotted and fixed. ta.
Kev