C#创建IIS站点及相应的应用程序池,支持IIS6.0+Windows Server 2003. 使用Builder设计模式
- 测试项目结构:

PS:IIS6UtilsBuilder, IIS7UtilsBuilder,IISUtilsBuilder以及IISDirector为Builder设计模式实现的核心代码。Program中入口函数则利用反射生成Builder实体,具体实现逻辑及详细代码见下:
- 详细代码
CmdUtil.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text; namespace SetupIISApp
{
/// <summary>
/// 运行bat文件
/// </summary>
public static class CmdUtils
{
/// <summary>
/// 执行bat文件
/// </summary>
/// <param name="path"></param>
public static void RunBatFile(string filePath)
{
Process proc = null;
try
{
var batFileName = Path.GetFileName(filePath);
var directoryPath = Path.GetDirectoryName(filePath);
string targetDir = string.Format(directoryPath) + "\\";
proc = new Process();
proc.StartInfo.WorkingDirectory = targetDir;
proc.StartInfo.FileName = batFileName;
proc.StartInfo.Arguments = string.Format("");
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//这里设置DOS窗口不显示,经实践可行
proc.Start();
proc.WaitForExit();
}
catch (Exception ex)
{
throw new Exception(string.Format("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString()));
}
}
}
}
IISDirector.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace SetupIISApp
{
public class IISDirector
{
/// <summary>
/// 路径
/// </summary>
public string Path { get; set; }
/// <summary>
/// 应用程序名
/// </summary>
public string AppName { get; set; }
public IISDirector()
{ }
public IISDirector(string path,string appName)
{
this.Path = path;
this.AppName = appName;
}
/// <summary>
/// 组装函数
/// </summary>
/// <param name="builder"></param>
public void Construct(IISUtilsBuilder builder)
{ builder.SetIISEnviorment(this.Path);
builder.RegNetFramework_v4_0_30319(this.Path);
builder.Delete(this.AppName);
builder.CreateAppliaction(this.AppName,this.Path);
}
}
}
IISUtilsBuilder.cs
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace SetupIISApp
{
public abstract class IISUtilsBuilder
{
/// <summary>
/// IIS版本
/// </summary>
public static Version IISVersion
{
get
{
object obj = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters", "MajorVersion", "");
//WebServerTypes ver = WebServerTypes.Unknown;
System.Version ver = new Version();
int major = ;
int minor = ;
if (obj != null)
{
major = Convert.ToInt32(obj);
}
obj = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters", "MinorVersion", "");
if (obj != null)
{
minor = Convert.ToInt32(obj);
} return new Version(major, minor); }
}
/// <summary>
/// 配置IIS windows Server 2003 IIS6.0环境
/// </summary>
/// <param name="path"></param>
public abstract void SetIISEnviorment(string path); /// <summary>
/// 非windows server2003操作系统且IIS版本为6.xs时注册NetFramework_v4_0_30319
/// </summary>
public abstract void RegNetFramework_v4_0_30319(string path); /// <summary>
/// 创建应用程序
/// </summary>
/// <param name="appName"></param>
/// <param name="path"></param>
public abstract void CreateAppliaction(string appName, string path); /// <summary>
/// 删除应用程序
/// </summary>
/// <param name="name">应用程序名称</param>
/// <returns></returns>
public abstract bool Delete(string name); }
}
IIS6UtilsBuilder.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices; namespace SetupIISApp
{
public class IIS6UtilsBuilder : IISUtilsBuilder
{
public override void SetIISEnviorment(string path)
{
//设置IIS
var frameWork4Path = "";
if (Environment.Is64BitOperatingSystem) // 调用命令更新应用程序池属性
{
frameWork4Path = FileUtils.GetWindowsDirectory() + @"\Microsoft.NET\Framework64\v4.0.30319";
}
else
{
frameWork4Path = FileUtils.GetWindowsDirectory() + @"\Microsoft.NET\Framework\v4.0.30319";
}
var sb = new StringBuilder();
sb.Append("cd " + FileUtils.GetWindowsDirectory() + @"\system32" + Environment.NewLine);
sb.Append(FileUtils.GetWindowsDirectory() + @"\system32\wscript.exe /h:cscript //B" + Environment.NewLine);
sb.Append("cmd.exe /c " + frameWork4Path + @"\aspnet_regiis.exe -i" + Environment.NewLine);
sb.Append(@"cd " + frameWork4Path + Environment.NewLine);
sb.Append("aspnet_regiis.exe -norestart -s W3SVC/1/ROOT" + Environment.NewLine);
sb.Append("cd " + FileUtils.GetWindowsDirectory() + @"\system32" + Environment.NewLine);
sb.Append("cmd.exe /c " + FileUtils.GetWindowsDirectory() + "\\system32\\iisext.vbs /EnApp \"ASP.NET v4.0.30319\"");
string fileContent = sb.ToString();
//生成bat文件
FileUtils.WriteBatFile(path + @"\IISSet.bat", fileContent);
//运行bat文件
CmdUtils.RunBatFile(path + @"\IISSet.bat");
//删除bat文件
FileUtils.DeleteFile(path + @"\IISSet.bat");
}
/// <summary>
///非windows server 2003操作系统时 IIS6.0 时注册NetFramework_v4_0_30319
/// </summary>
public override void RegNetFramework_v4_0_30319(string path)
{
var frameWork4Path = "";
if (Environment.Is64BitOperatingSystem) // 调用命令更新应用程序池属性
{
frameWork4Path = FileUtils.GetWindowsDirectory() + @"\Microsoft.NET\Framework64\v4.0.30319";
}
else
{
frameWork4Path = FileUtils.GetWindowsDirectory() + @"\Microsoft.NET\Framework\v4.0.30319";
}
var sb = new StringBuilder();
sb.Append("cmd.exe /c " + frameWork4Path + @"\aspnet_regiis.exe -i" + Environment.NewLine);
string fileContent = sb.ToString();
//生成bat文件
FileUtils.WriteBatFile(path + @"\NetReg.bat", fileContent);
//运行bat文件
CmdUtils.RunBatFile(path + @"\NetReg.bat");
//删除bat文件
FileUtils.DeleteFile(path + @"\NetReg.bat");
}
public override void CreateAppliaction(string appName, string path)
{
bool isWindowsServer2003 = Environment.OSVersion.Version.Major == && Environment.OSVersion.Version.Minor == ;
////创建应用程序池
DirectoryEntry appPoolRoot = new DirectoryEntry(@"IIS://localhost/W3SVC/AppPools");
var createAppPool = true;
foreach (DirectoryEntry e in appPoolRoot.Children)
{
if (e.Name == appName)
{
createAppPool = false;
}
}
if (createAppPool)
{
DirectoryEntry newAppPool = appPoolRoot.Children.Add(appName, "IIsApplicationPool");
newAppPool.Properties["AppPoolQueueLength"][] = "";
//禁用回收 回收>>>固定时间间隔
newAppPool.Properties["PeriodicRestartTime"][] = "";
//闲置超时
newAppPool.Properties["IdleTimeout"][] = ""; newAppPool.Properties["AppPoolIdentityType"][] = "";
if (!isWindowsServer2003)//windows server2003
{
newAppPool.Properties["ManagedRuntimeVersion"][] = "v4.0";//Net版本号//windows server2003不支持
newAppPool.Properties["ManagedPipelineMode"][] = "";//0:集成模式 1:经典模式windows server2003不支持
newAppPool.Properties["Enable32BitAppOnWin64"][] = true; //windows server2003不支持
newAppPool.CommitChanges();
}
else
{
newAppPool.CommitChanges();
}
}
//default website所在路径
DirectoryEntry de = new DirectoryEntry("IIS://localhost/W3SVC/1/Root");
de.RefreshCache();
foreach (DirectoryEntry e in de.Children)
{
if (e.Name == appName)
{
//删除已有应用程序
de.Children.Remove(e);
}
}
DirectoryEntry myde = de.Children.Add(appName, "IIsWebVirtualDir");
myde.Properties["Path"].Insert(, path);//插入到IIS
myde.Invoke("AppCreate", true);//创建
myde.Properties["AppPoolId"][] = appName;
myde.Properties["AuthAnonymous"][] = true;//允许匿名访问
myde.Properties["AccessRead"][] = true; //开启读取
myde.Properties["AccessScript"][] = true;//脚本可执行
//设置是否禁用日志 默认为false。
myde.Properties["DontLog"][] = true;
myde.CommitChanges();//保存更改
de.CommitChanges();
de.Close();
myde.Close();
myde.Dispose();
de.Dispose();
}
public override bool Delete(string name)
{
bool isOk = false;
try
{
using (DirectoryEntry defaultSite = new DirectoryEntry("IIS://localhost/W3SVC/1/ROOT"))
{
foreach (DirectoryEntry dir in defaultSite.Children)
{
if (dir.Name == name && dir.SchemaClassName == "IIsWebVirtualDir")
{
defaultSite.Children.Remove(dir);
isOk = true;
break;
}
}
defaultSite.CommitChanges();
}
AppPoolDelete(name);
}
catch
{
}
return isOk;
} /// <summary>
/// 删除应用程序池
/// </summary>
/// <param name="name">应用程序池名称</param>
/// <returns>成功返回 true,否则返回 false</returns>
private bool AppPoolDelete(string name)
{
bool isOk = false;
DirectoryEntry pool = AppPoolOpen(name);
if (pool != null)
{
pool.DeleteTree();
isOk = true;
}
return isOk;
}
/// <summary>
/// 返回应用程序池实例
/// </summary>
/// <param name="name">应用程序池名称</param>
/// <returns>应用程序池实例</returns>
private DirectoryEntry AppPoolOpen(string name)
{
using (DirectoryEntry pools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools"))
{
foreach (DirectoryEntry entry in pools.Children)
{
if (entry.SchemaClassName == "IIsApplicationPool" && entry.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase))
{
return entry;
}
}
return null;
}
}
}
}
IIS7UtilsBuilder.cs
using Microsoft.Web.Administration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace SetupIISApp
{
public class IIS7UtilsBuilder : IISUtilsBuilder
{
public override void SetIISEnviorment(string path)
{ }
public override void RegNetFramework_v4_0_30319(string path)
{ }
public override void CreateAppliaction(string appName, string path)
{
try
{
if (!AppPoolExists(appName))
{
AppPoolCreate(appName);
}
using (ServerManager sm = new ServerManager())
{
// sm.Sites.Add("test", @"D:\DataBackup", 9898);//添加新站点 Site site = sm.Sites["Default Web Site"];
if (site != null)
{
site.LogFile.Enabled = false;
Application app = site.Applications["/" + appName];
if (app == null)
{
app = site.Applications.Add("/" + appName, path);
app.ApplicationPoolName = appName;
}
sm.CommitChanges();
}
}
}
catch (Exception ex)
{
throw ex;
}
}
public override bool Delete(string name)
{
bool isOk = false;
try
{
using (ServerManager sm = new ServerManager())
{
Site site = sm.Sites["Default Web Site"];
if (site != null)
{
site.LogFile.Enabled = true;
Application app = site.Applications["/" + name];
if (app != null)
{
site.Applications.Remove(app);
}
sm.CommitChanges();
}
}
AppPoolDelete(name);
isOk = true;
}
catch (Exception ex)
{
throw ex;
}
return isOk; } /// <summary>
/// 删除应用程序池
/// </summary>
/// <param name="name">应用程序池名称</param>
/// <returns>成功返回 true,否则返回 false</returns>
private void AppPoolDelete(string name)
{
using (ServerManager sm = new ServerManager())
{
ApplicationPool pool = sm.ApplicationPools[name];
if (pool != null)
{
sm.ApplicationPools.Remove(sm.ApplicationPools[name]);
sm.CommitChanges();
}
}
}
/// <summary>
/// 创建应用程序池
/// </summary>
/// <param name="name">要创建应用程序池的名称</param>
/// <returns>如果创建成功返回 IIS7AppPool,否则返回 null</returns>
private void AppPoolCreate(string name)
{
using (ServerManager sm = new ServerManager())
{
ApplicationPool pool = sm.ApplicationPools[name];
if (pool == null)
{
pool = sm.ApplicationPools.Add(name);
pool.ManagedPipelineMode = ManagedPipelineMode.Integrated;/*集成*/
//pool.ProcessModel.IdentityType = ProcessModelIdentityType.ApplicationPoolIdentity;
pool.ProcessModel.IdentityType = ProcessModelIdentityType.NetworkService;
pool.Enable32BitAppOnWin64 = true;
pool.ManagedRuntimeVersion = "v4.0";
pool.Failure.RapidFailProtection = true;
pool.QueueLength = ;
//禁用回收 回收>>>固定时间间隔
pool.Recycling.PeriodicRestart.Time = new TimeSpan();
//闲置超时
pool.ProcessModel.IdleTimeout = new TimeSpan();
sm.CommitChanges();
}
}
}
/// <summary>
/// 应用程序池是否存在 /// </summary>
/// <param name="name">应用程序池名称</param>
/// <returns>存在则返回 true,否则返回 false</returns>
private bool AppPoolExists(string name)
{
using (ServerManager sm = new ServerManager())
{
return sm.ApplicationPools[name] != null;
}
}
}
}
FileUtils.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text; namespace SetupIISApp
{
public static class FileUtils
{
[DllImport("kernel32")]
private static extern void GetWindowsDirectory(StringBuilder WinDir, int count);
/// <summary>
/// 获取windows 目录文件
/// </summary>
/// <param name="count"></param>
/// <returns></returns> public static string GetWindowsDirectory()
{
int count = ;
StringBuilder sb = new StringBuilder();
GetWindowsDirectory(sb, count);
return sb.ToString();
}
/// <summary>
/// 生成bat文件
/// </summary>
/// <param name="batFilePath"></param>
/// <param name="fileContent"></param>
public static void WriteBatFile(string batFilePath, string fileContent)
{
//生成bat文件
if (!File.Exists(batFilePath))
{
FileStream fs1 = new FileStream(batFilePath, FileMode.Create, FileAccess.Write);//创建写入文件
StreamWriter sw = new StreamWriter(fs1);
sw.WriteLine(fileContent);//开始写入值
sw.Close();
fs1.Close();
}
else//更新bat文件
{
FileStream fs = new FileStream(batFilePath, FileMode.Open, FileAccess.Write);
StreamWriter sr = new StreamWriter(fs);
sr.WriteLine(fileContent);//开始写入值
sr.Close();
fs.Close();
}
}
/// 删除某文件
/// </summary>
/// <param name="srcPath">目标路径</param>
public static void DeleteFile(string srcPath)
{
try
{
//删除文件
if (File.Exists(srcPath))
{
var fileInfo = new FileInfo(srcPath);
fileInfo.Attributes = FileAttributes.Normal;
fileInfo.Delete();
}
}
catch
{
}
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text; namespace SetupIISApp
{
class Program
{
static void Main(string[] args)
{
string builderStr = "";
bool isWindowsServer2003 = Environment.OSVersion.Version.Major == && Environment.OSVersion.Version.Minor == ;
if (isWindowsServer2003)
{
builderStr = "IIS6UtilsBuilder";
}
else
{
if (IISUtilsBuilder.IISVersion.Major < )
{
builderStr = "IIS6UtilsBuilder";
}
else
{
builderStr = "IIS7UtilsBuilder";
}
}
string path = @"D:\发布\TestWeb";
string name = @"SetIISTest";
var director = new IISDirector(path, name);
//反射生成builder实体
var builder = (IISUtilsBuilder)Assembly.Load("SetupIISApp").CreateInstance("SetupIISApp." + builderStr);
director.Construct(builder);
}
}
}
- 运行结果

以上为本片博文的全部内容,在IIS6.0环境中创建站点还暂未包括在本项目中,都以应用程序的模式挂载在默认[default web site]站点下。
此博文为原创,转载请注明出处!!!!!
C#创建IIS站点及相应的应用程序池,支持IIS6.0+Windows Server 2003. 使用Builder设计模式的更多相关文章
- 使用appcmd命令创建iis站点及应用程序池
参考文章:iis7 appcmd的基础命令及简单用法 验证环境:Windows 7 IIS7 AppCmd.exe工具所在目录 C:\windows\sytstem32\inetsrv\目录下, ...
- 如何在Windows Server 2003中配置FTP站点服务
前面写过一篇文章<怎样给你的网站注册一个好域名?> ,讲到“玉米”,笔者有很深的情节,也希望与大家交流“米事”,可以站内私信我或者直接回复文章. 有了好域名只是做网站的开始.我们还要买主机 ...
- Windows Server 2003 IIS设置完全篇
一.启用Asp支持Windows Server 2003 默认安装,是不安装 IIS 6 的,需要另外安装.安装完 IIS 6,还需要单独开启对于 ASP 的支持. 第一步,启用Asp,进入:控制面板 ...
- Windows Server 2003 动态网站IIS设置(图)
一.安装IIS Windows Server 2003 虽说是服务器版本,但在默认情况下并没有安装IIS,要在本地浏览asp,PHP等动态网页,就必须安装IIS.在买系统盘的时候,请注意看一下 ...
- IIS隐藏版本号教程(Windows Server 2003)
1.下载Urlscan https://www.microsoft.com/en-us/search/DownloadResults.aspx?q=URLScan(总下载页面) https://dow ...
- 用户收到"无法显示页面"的错误消息和"Connections_refused"条目记录在运行 Windows Server 2003,Exchange 2003 和 IIS 6.0 的服务器上的 Httperr.log 文件
症状 您会遇到下列症状在运行 Microsoft Windows Server 2003. Microsoft Exchange Server 2003年和 Microsoft Internet In ...
- C# 创建iis站点以及IIS站点属性,iis不能启动站点
DontLog = False是否将客户端的请求写入日志文件 2011年04月09日 #region CreateWebsite 新增网站 public string CreateWebSite(st ...
- 通过代码动态创建IIS站点
对WebApi进行单元测试时,一般需要一个IIS站点,一般的做法,是通过写一个批处理的bat脚本来实现,其实通过编码,也能实现该功能. 主要有关注三点:应用程序池.Web站点.绑定(协议类型:http ...
- cmd 批处理创建 IIS 站点
windows 创建站点命令 appcmd C:\Windows\System32\inetsrv\appcmd.exe SITE 虚拟站点的管理 APP 管理应用程序 VDIR 管理虚拟目录 APP ...
随机推荐
- 【英国毕业原版】-《伯明翰城市大学毕业证书》BCU一模一样原件
☞伯明翰城市大学毕业证书[微/Q:865121257◆WeChat:CC6669834]UC毕业证书/联系人Alice[查看点击百度快照查看][留信网学历认证&博士&硕士&海归 ...
- 基于promtheus的监控解决方案
一.前言 鄙人就职于某安全公司,团队的定位是研发安全产品云汇聚平台,为用户提供弹性伸缩的云安全能力.前段时间产品组提出了一个监控需求,大致要求:平台对vm实行动态实时监控,输出相应图表界面,并提供警报 ...
- ASP.NET Core2.1 你不得不了解的GDPR(Cookie处理)
前言 时间一晃 ASP.NET Core已经迭代到2.1版本了. 迫不及待的的下载了最新的版本,然后生成了一个模版项目来试试水. ...然后就碰到问题了... 我发现..cookie竟然存不进去了.. ...
- [asp.net mvc 奇淫巧技] 06 - 也许你的项目同一个用户的请求都是同步的
一.感慨 很久前看到一篇博客中有句话大致的意思是:“asp.net 程序性能低下的主要原因是开发人员技术参差不齐”,当时看到这句话不以为然,然而时间过的越久接触的.net 开发人员越多就越认同这句话: ...
- Python爬虫入门教程 59-100 python爬虫高级技术之验证码篇5-极验证识别技术之二
图片比对 昨天的博客已经将图片存储到了本地,今天要做的第一件事情,就是需要在两张图片中进行比对,将图片缺口定位出来 缺口图片 完整图片 计算缺口坐标 对比两张图片的所有RBG像素点,得到不一样像素点的 ...
- 目前比较流行的Python量化开源框架汇总(交易+风险分析工具)
注:点击框架名称通往Github talib talib的简称是Technical Analysis Library,主要功能是计算行情数据的技术分析指标 numpy 介绍:一个用python实现的 ...
- 阿里云卸载自带的JDK,安装JDK完成相关配置
0.预备工作 笔者的云服务器购买的是阿里云的轻量应用服务器,相比于云服务器ECS,轻量应用服务器是固定流量但是网络带宽较高,对于服务器来说,网络带宽是非常昂贵的,而带宽也决定了你的应用访问的流畅度,带 ...
- ES 集群上,业务单点如何优化升级?
摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠BYSocket 」欢迎关注和转载,保留摘要,谢谢! ES 基础 ES 集群 ES 集群上业务优化 一.ES 基础 ...
- Python爬虫使用lxml模块爬取豆瓣读书排行榜并分析
上次使用了BeautifulSoup库爬取电影排行榜,爬取相对来说有点麻烦,爬取的速度也较慢.本次使用的lxml库,我个人是最喜欢的,爬取的语法很简单,爬取速度也快. 本次爬取的豆瓣书籍排行榜的首页地 ...
- Java并发编程面试题 Top 50 整理版
本文在 Java线程面试题 Top 50的基础上,对部分答案进行进行了整理和补充,问题答案主要来自<Java编程思想(第四版)>,<Java并发编程实战>和一些优秀的博客,当然 ...