簡體   English   中英

如何從 c# 中刪除 IIS 對象?

[英]How can I delete IIS objects from c#?

作為卸載方法的一部分,我需要從 .NET 中刪除虛擬目錄和應用程序池。 我在某處的 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.");
        }
    }

但它似乎在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 object,然后為其父項創建一個DirectoryEntry 然后您告訴父母刪除 object。

您也可以這樣做:

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

根據手頭的任務,我將使用任何一種方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM