部署時自動建立專屬應用程式池、虛擬目錄並關聯,適合 MSI 安裝腳本。
using System;
using System.DirectoryServices;
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)
{
Console.WriteLine("\nCreating application pool {0}/{1}:", metabasePath, appPoolName);
try
{
if (metabasePath.EndsWith("/W3SVC/AppPools"))
{
DirectoryEntry apppools = new DirectoryEntry(metabasePath);
DirectoryEntry newpool = apppools.Children.Add(appPoolName, "IIsApplicationPool");
newpool.CommitChanges();
Console.WriteLine(" Done.");
}
else Console.WriteLine(" Failed: must create under AppPools node.");
}
catch (Exception ex) { Console.WriteLine("Failed: {0}", ex.Message); }
}
static void CreateVDir(string metabasePath, string vDirName, string physicalPath)
{
Console.WriteLine("\nCreating virtual directory {0}/{1} -> {2}:", metabasePath, vDirName, physicalPath);
try
{
DirectoryEntry site = new DirectoryEntry(metabasePath);
string className = site.SchemaClassName;
if (className.EndsWith("Server") || className.EndsWith("VirtualDir"))
{
DirectoryEntry newVDir = site.Children.Add(vDirName, className.Replace("Service", "VirtualDir"));
newVDir.Properties["Path"][0] = physicalPath;
newVDir.Properties["AccessScript"][0] = true;
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: only under site or vdir node.");
}
catch (Exception ex) { Console.WriteLine("Failed: {0}", ex.Message); }
}
static void AssignVDirToAppPool(string metabasePath, string appPoolName)
{
Console.WriteLine("\nAssigning {0} to app pool {1}:", metabasePath, appPoolName);
try
{
DirectoryEntry vDir = new DirectoryEntry(metabasePath);
if (vDir.SchemaClassName.EndsWith("VirtualDir"))
{
vDir.Invoke("AppCreate3", new object[] { 0, appPoolName, true });
vDir.Properties["AppIsolated"][0] = "2";
Console.WriteLine(" Done.");
}
else Console.WriteLine(" Failed: only virtual directories can be assigned.");
}
catch (Exception ex) { Console.WriteLine("Failed: {0}", ex.Message); }
}
}
}
出處:https://mqsuper.cnblogs.com