Reputation: 7830
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.
Upvotes: 1
Views: 2411
Reputation: 141638
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();
}
}
Upvotes: 4
Reputation: 6506
Each WebSite has a different Id - the LDAP address of the "MySite" is probably something like this:
IIS://" + this._serverName + "/W3SVC/**2**/Root
Upvotes: 1