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?
If you’re deleting objects such as application pools, virtual directories or IIS applications, you need to do it like this:
You create a
DirectoryEntryobject for the item you want to delete then create aDirectoryEntryfor its parent. You then tell the parent to remove that object.You can also do this as well:
Depending on the task in hand I’ll use either method.