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

时间:2011-11-20 15:42:11

标签: c# .net iis-7

  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"时,它会给我错误。

2 个答案:

答案 0 :(得分:4)

这一行:

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

始终采用默认网站。 “1”是网站的ID。将“1”替换为您要在其中创建虚拟目录的站点的ID。您可以在IIS中找到站点ID:

enter image description here

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

答案 1 :(得分:1)

每个网站都有不同的ID - “MySite”的LDAP地址可能是这样的:

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