Creating IIS Virtual Directories

I found the need one time to create a virtual directory in IIS programmatically through an installer. I did this with a .NET application by utilizing the directory services objects and a bit of research on the web. Most of the answers came from hints on forums, but one article of particular help, A "Make Virtual Directory 2.0 Here" Windows Explorer Context Menu Utility, outlined some of the details in getting this to work.

The first challange is to create a method that handles both IIS 5 and IIS 6 or later installations since the later introduced application pools. Creating an application pool might be done in this way:

string poolName = "MyPool";
DirectoryEntry appPoolRoot = new DirectoryEntry(@"IIS://localhost/W3SVC/AppPools");
DirectoryEntry appPool = appPoolRoot.Children.Add(poolName, "IISApplicationPool");
appPool.Properties["AppPoolIdentityType"][0] = "2";
appPool.CommitChanges();

Next, the virtual directory object is set up as a child of the root object and configured with some virtual directory specific settings.

string vdirName = "MySite";
string vdirPath = @"C:\inetpub\wwwroot\...";
DirectoryEntry dirWebRoot = new DirectoryEntry("IIS://localhost/W3SVC/1/Root");
DirectoryEntry = dirWebRoot.Children.Add(vdirName, "IIsWebVirtualDir");
dirVirtual.Properties["AppFriendlyName"][0] = vdirName;
dirVirtual.Properties["Path"][0] = vdirPath;

Now we can set up some of the sites properties such as permissions, authentication, settings, etc.

bool makeSecure = true;
bool underNT = (new DirectoryEntry("IIS://localhost/Schema/AppIsolated").Properties["Syntax"].Value.ToString().ToUpper() == "BOOLEAN");

dirVirtual.Properties["DontLog"][0] = false;
dirVirtual.Properties["AccessScript"][0] = false;
dirVirtual.Properties["AccessRead"][0] = true;
dirVirtual.Properties["AccessWrite"][0] = false;
dirVirtual.Properties["AccessScript"][0] = true;
dirVirtual.Properties["AuthAnonymous"][0] = !makeSecure;
dirVirtual.Properties["AuthNTLM"][0] = true;
dirVirtual.Properties["EnableDefaultDoc"][0] = true;
dirVirtual.Properties["EnableDirBrowsing"][0] = false;
dirVirtual.Properties["DefaultDoc"][0] = "default.htm";
if (!underNT)
   dirVirtual.Properties["AspEnableParentPaths"][0] = true;
if (poolName != null)
   dirVirtual.Properties["AppPoolId"][0] = poolName;

dirVirtual.CommitChanges();

if (underNT)
   dirVirtual.Invoke("AppCreate", false);
else
   dirVirtual.Invoke("AppCreate2", new object[] { 2 });

You may also want to run aspnet_regiis.exe if you need to register the virtual directory for a specific version of the .NET framework.