Skip to main content
 首页 » 编程设计

c#之在特定网站中使用 C# 创建 Web IIS 虚拟目录

2024年02月03日25pander-it

  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。将“1”替换为您要在其中创建虚拟目录的站点的 ID。您可以在此处的 IIS 中找到站点 ID:

如果需要,您还可以使用目录服务以编程方式枚举所有网站,以帮助您找到正确的 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(); 
   }           
}