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?
In the Application Pools explorer, right-click the application pool and click Delete.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With