Creating Application Pools Using System.DirectoryServices
Internet Service Providers (ISPs) that provide Web hosting services to customers need to configure their IIS servers frequently. Some ISPs use forms to programmatically enroll a new customer and add a new Web site or virtual directory for them. The new site or virtual directory can be put in a new application pool to isolate it from other applications on the server.
Example Code
The following example shows you how to use the C# programming language to create a new application pool, then create a virtual directory and assign it to the new application pool.
Note
In IIS 5.1 and earlier versions, application pools are not available.
To keep this code example concise, it does not include code access security (CAS) parameters or parameter checking. For more information, see Code Access Security and Validating User Input to Avoid Attacks. Additionally, you can instantiate your System.DirectoryServices.DirectoryEntry object with an authentication parameter.
using System;
using System.IO;
using System.DirectoryServices;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Collections;
namespace System_DirectoryServices_DirectoryEntry_ConfigIIS
{
class Program
{
static void Main(string[] args)
{
...
CreateAppPool("IIS://Localhost/W3SVC/AppPools", "MyAppPool");
...
CreateVDir("IIS://Localhost/W3SVC/1/Root", "MyVDir", "D:\\Inetpub\\Wwwroot");
...
AssignVDirToAppPool("IIS://Localhost/W3SVC/1/Root/MyVDir", "MyAppPool");
...
}
...
static void CreateAppPool(string metabasePath, string appPoolName)
{
// metabasePath is of the form "IIS://<servername>/W3SVC/AppPools"
// for example "IIS://localhost/W3SVC/AppPools"
// appPoolName is of the form "<name>", for example, "MyAppPool"
Console.WriteLine("\nCreating application pool named {0}/{1}:", metabasePath, appPoolName);
try
{
if (metabasePath.EndsWith("/W3SVC/AppPools"))
{
DirectoryEntry newpool;
DirectoryEntry apppools = new DirectoryEntry(metabasePath);
newpool = apppools.Children.Add(appPoolName, "IIsApplicationPool");
newpool.CommitChanges();
Console.WriteLine(" Done.");
}
else
Console.WriteLine(" Failed in CreateAppPool; application pools can only be created in the */W3SVC/AppPools node.");
}
catch (Exception ex)
{
Console.WriteLine("Failed in CreateAppPool with the following exception: \n{0}", ex.Message);
}
}
...
static void CreateVDir(string metabasePath, string vDirName, string physicalPath)
{
// metabasePath is of the form "IIS://<servername>/<service>/<siteID>/Root[/<vdir>]"
// for example "IIS://localhost/W3SVC/1/Root"
// vDirName is of the form "<name>", for example, "MyNewVDir"
// physicalPath is of the form "<drive>:\<path>", for example, "C:\Inetpub\Wwwroot"
Console.WriteLine("\nCreating virtual directory {0}/{1}, mapping the Root application to {2}:",
metabasePath, vDirName, physicalPath);
try
{
DirectoryEntry site = new DirectoryEntry(metabasePath);
string className = site.SchemaClassName.ToString();
if ((className.EndsWith("Server")) || (className.EndsWith("VirtualDir")))
{
DirectoryEntries vdirs = site.Children;
DirectoryEntry newVDir = vdirs.Add(vDirName, (className.Replace("Service", "VirtualDir")));
newVDir.Properties["Path"][0] = physicalPath;
newVDir.Properties["AccessScript"][0] = true;
// These properties are necessary for an application to be created.
newVDir.Properties["AppFriendlyName"][0] = vDirName;
newVDir.Properties["AppIsolated"][0] = "1";
newVDir.Properties["AppRoot"][0] = "/LM" + metabasePath.Substring(metabasePath.IndexOf("/", ("IIS://".Length)));
newVDir.CommitChanges();
Console.WriteLine(" Done.");
}
else
Console.WriteLine(" Failed. A virtual directory can only be created in a site or virtual directory node.");
}
catch (Exception ex)
{
Console.WriteLine("Failed in CreateVDir with the following exception: \n{0}", ex.Message);
}
}
...
static void AssignVDirToAppPool(string metabasePath, string appPoolName)
{
// metabasePath is of the form "IIS://<servername>/W3SVC/<siteID>/Root[/<vDir>]"
// for example "IIS://localhost/W3SVC/1/Root/MyVDir"
// appPoolName is of the form "<name>", for example, "MyAppPool"
Console.WriteLine("\nAssigning application {0} to the application pool named {1}:", metabasePath, appPoolName);
try
{
DirectoryEntry vDir = new DirectoryEntry(metabasePath);
string className = vDir.SchemaClassName.ToString();
if (className.EndsWith("VirtualDir"))
{
object[] param = { 0, appPoolName, true };
vDir.Invoke("AppCreate3", param);
vDir.Properties["AppIsolated"][0] = "2";
Console.WriteLine(" Done.");
}
else
Console.WriteLine(" Failed in AssignVDirToAppPool; only virtual directories can be assigned to application pools");
}
catch (Exception ex)
{
Console.WriteLine("Failed in AssignVDirToAppPool with the following exception: \n{0}", ex.Message);
}
}
...
}
}
Imports System
Imports System.IO
Imports System.DirectoryServices
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Collections
Module Program
Sub Main(ByVal args() As String)
...
CreateVDir("IIS://Localhost/W3SVC/1/Root", "MyVDir", "D:\Inetpub\Wwwroot")
...
AssignVDirToAppPool("IIS://Localhost/W3SVC/1/Root/MyVDir", "MyAppPool")
...
End Sub
...
Sub CreateAppPool(ByVal strMetabasePath As String, ByVal strAppPoolName As String)
' strMetabasePath is of the form "IIS://<servername>/W3SVC/AppPools"
' For example: "IIS://localhost/W3SVC/AppPools"
' strAppPoolName is of the form "<name>", for example, "MyAppPool"
Console.WriteLine(vbLf + "Creating application pool named {0}/{1}:", strMetabasePath, strAppPoolName)
Try
If strMetabasePath.EndsWith("/W3SVC/AppPools") Then
Dim objNewPool As DirectoryEntry
Dim objAppPools As New DirectoryEntry(strMetabasePath)
objNewPool = objAppPools.Children.Add(strAppPoolName, "IIsApplicationPool")
objNewPool.CommitChanges()
Console.WriteLine("Done.")
Else
Console.WriteLine("Failed in CreateAppPool; application pools can only be created in the */W3SVC/AppPools node.")
End If
Catch exError As Exception
Console.WriteLine("Failed in CreateAppPool with the following exception: " + vbLf + "{0}", exError.Message)
End Try
End Sub
...
Sub CreateVDir(ByVal strMetabasePath As String, ByVal strVdirName As String, ByVal strPhysicalPath As String)
' strMetabasePath is of the form "IIS://<servername>/<service>/<siteID>/Root[/<vdir>]"
' For example: "IIS://localhost/W3SVC/1/Root"
' strVdirName is of the form "<name>", for example, "MyNewVDir"
' strPhysicalPath is of the form "<drive>:\<path>", for example, "C:\Inetpub\Wwwroot"
Console.WriteLine(vbLf + "Creating virtual directory {0}/{1}, mapping the Root application to {2}:", strMetabasePath, strVdirName, strPhysicalPath)
Try
Dim objSite As New DirectoryEntry(strMetabasePath)
Dim strClassName As String = objSite.SchemaClassName.ToString()
If strClassName.EndsWith("Server") OrElse strClassName.EndsWith("VirtualDir") Then
Dim objVdirs As DirectoryEntries = objSite.Children
Dim objNewVdir As DirectoryEntry = objVdirs.Add(strVdirName, strClassName.Replace("Service", "VirtualDir"))
objNewVdir.Properties("Path")(0) = strPhysicalPath
objNewVdir.Properties("AccessScript")(0) = True
' These properties are necessary for an application to be created.
objNewVdir.Properties("AppFriendlyName")(0) = strVdirName
objNewVdir.Properties("AppIsolated")(0) = "1"
objNewVdir.Properties("AppRoot")(0) = "/LM" + strMetabasePath.Substring(strMetabasePath.IndexOf("/", "IIS://".Length))
objNewVdir.CommitChanges()
Console.WriteLine("Done.")
Else
Console.WriteLine("Failed. A virtual directory can only be created in a site or virtual directory node.")
End If
Catch exError As Exception
Console.WriteLine("Failed in CreateVDir with the following exception: " + vbLf + "{0}", exError.Message)
End Try
End Sub
...
Sub AssignVDirToAppPool(ByVal strMetabasePath As String, ByVal strAppPoolName As String)
' strMetabasePath is of the form "IIS://<servername>/W3SVC/<siteID>/Root[/<vDir>]"
' For example: "IIS://localhost/W3SVC/1/Root/MyVDir"
' strAppPoolName is of the form "<name>", for example, "MyAppPool"
Console.WriteLine(vbLf + "Assigning application {0} to the application pool named {1}:", strMetabasePath, strAppPoolName)
Try
Dim objVdir As New DirectoryEntry(strMetabasePath)
Dim strClassName As String = objVdir.SchemaClassName.ToString()
If strClassName.EndsWith("VirtualDir") Then
Dim objParam As Object() = {0, strAppPoolName, True}
objVdir.Invoke("AppCreate3", objParam)
objVdir.Properties("AppIsolated")(0) = "2"
Console.WriteLine("Done.")
Else
Console.WriteLine("Failed in AssignVDirToAppPool; only virtual directories can be assigned to application pools")
End If
Catch exError As Exception
Console.WriteLine("Failed in AssignVDirToAppPool with the following exception: " + vbLf + "{0}", exError.Message)
End Try
End Sub
...
End Module