簡體   English   中英

在特定網站上使用C#創建Web IIS虛擬目錄

[英]Create Web IIS Virtual Directory using C# in particular web site

  public void CreateVirtualDirectory(string nameDirectory, string realPath)
        {
            System.DirectoryServices.DirectoryEntry oDE;
            System.DirectoryServices.DirectoryEntries oDC;
            System.DirectoryServices.DirectoryEntry oVirDir;
            try
            {

                oDE = new DirectoryEntry("IIS://" + this._serverName + "/W3SVC/1/Root");

                //Get Default Web Site
                oDC = oDE.Children;

                //Add row
                oVirDir = oDC.Add(nameDirectory, oDE.SchemaClassName.ToString());

                //Commit changes for Schema class File
                oVirDir.CommitChanges();

                //Create physical path if it does not exists
                if (!Directory.Exists(realPath))
                {
                    Directory.CreateDirectory(realPath);
                }

                //Set virtual directory to physical path
                oVirDir.Properties["Path"].Value = realPath;

                //Set read access
                oVirDir.Properties["AccessRead"][0] = true;

                //Create Application for IIS Application (as for ASP.NET)

                oVirDir.Invoke("AppCreate", true);
                oVirDir.Properties["AppFriendlyName"][0] = nameDirectory;


                //Save all the changes
                oVirDir.CommitChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

上面的函數可以正常工作_serverName = "localhost"但是它總是在IIS的默認網站中創建虛擬目錄。 雖然我在localhost:8080上創建了另一個名為MySite的示例站點。 所以當我把_serverName = "localhost:8080"它給了我錯誤。

這行:

oDE = new DirectoryEntry("IIS://" + this._serverName + "/W3SVC/1/Root");

始終采用默認網站。 “ 1”是網站的ID。 用要在其中創建虛擬目錄的站點的ID替換“ 1”。您可以在IIS中找到站點的ID:

在此處輸入圖片說明

如果需要,您還可以使用Directory Services以編程方式枚舉所有網站,以幫助您找到正確的ID:

DirectoryEntry w3svc = new DirectoryEntry("IIS://" + this._serverName + "/w3svc");

foreach(DirectoryEntry de in w3svc.Children)
{
   if(de.SchemaClassName == "IIsWebServer")
   {
       var id = de.Name; //Name is the ID
       var displayName = de.Properties["ServerComment"].Value.ToString();
   }          
}

每個WebSite都有一個不同的ID-“ MySite”的LDAP地址可能是這樣的:

IIS://" + this._serverName + "/W3SVC/**2**/Root

暫無
暫無

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

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