简体   繁体   English

如何从 c# 中删除 IIS 对象?

[英]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.作为卸载方法的一部分,我需要从 .NET 中删除虚拟目录和应用程序池。 I found the following code on the web somewhere:我在某处的 web 上找到了以下代码:

    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();但它似乎在tree.CommitChanges();上抛出了COMException . . 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:如果要删除应用程序池、虚拟目录或 IIS 应用程序等对象,则需要这样做:

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.您为要删除的项目创建一个DirectoryEntry object,然后为其父项创建一个DirectoryEntry You then tell the parent to remove that object.然后您告诉父母删除 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.根据手头的任务,我将使用任何一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM