Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete IIS objects from c#?

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?

like image 738
Grzenio Avatar asked Mar 20 '09 17:03

Grzenio


People also ask

How do I get rid of application pools?

In the Application Pools explorer, right-click the application pool and click Delete.


1 Answers

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.

like image 175
Kev Avatar answered Sep 28 '22 10:09

Kev