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

标签 c# .net iis installation wmi

作为卸载方法的一部分,我需要从 .NET 中删除虚拟目录和应用程序池。我在网上某处找到了以下代码:

    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.");
        }
    }

但它似乎在 tree.CommitChanges(); 上抛出一个 COMException。我需要这条线吗?这是正确的做法吗?

最佳答案

如果您要删除应用程序池、虚拟目录或 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();
    }
}

您为要删除的项目创建一个 DirectoryEntry 对象,然后为其父项创建一个 DirectoryEntry。然后,您告诉 parent 移除该对象。

您也可以这样做:

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

根据手头的任务,我将使用任一方法。

关于c# - 如何从 C# 中删除 IIS 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/667243/

相关文章:

.net - 在 Sql server 2005 中过滤 unicode 列 - 多数据匹配

.net - VB.net动态添加用户控件

ASP.NET IIS Web.config [内部服务器错误]

ASP.NET MVC 间歇性 401 授权错误

winforms - WinForms 客户端和共享主机 Web 服务器之间的 WCF 安全性

c# - 从 WCF 服务流式传输文件

c# - 在c#中选择查询后获取表的ID

c# - 自定义 xmlWriter 跳过某个元素?

c# - JobHost 未检测到引用程序集中的 Azure HttpTriggers

c# - ToString() 格式不起作用