简体   繁体   中英

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;
            }
        }

This above function work fine _serverName = "localhost" but this always create virtual directory in Default Web Site in IIS. While I have another sample site created with name MySite on localhost:8080. so when I put _serverName = "localhost:8080" it gives me error.

This line:

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

Always assumes the default web site. The "1" is the ID of the website. Replace the "1" with the ID of the site you want to create the virtual directory in. You can find the site ID in the IIS here:

在此处输入图片说明

You can, if you desire, enumerate all of the websites programmatically using Directory Services as well to help you find the right 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM