• 测试项目结构:

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设计模式的更多相关文章

  1. 使用appcmd命令创建iis站点及应用程序池

    参考文章:iis7 appcmd的基础命令及简单用法 验证环境:Windows 7    IIS7 AppCmd.exe工具所在目录 C:\windows\sytstem32\inetsrv\目录下, ...

  2. 如何在Windows Server 2003中配置FTP站点服务

    前面写过一篇文章<怎样给你的网站注册一个好域名?> ,讲到“玉米”,笔者有很深的情节,也希望与大家交流“米事”,可以站内私信我或者直接回复文章. 有了好域名只是做网站的开始.我们还要买主机 ...

  3. Windows Server 2003 IIS设置完全篇

    一.启用Asp支持Windows Server 2003 默认安装,是不安装 IIS 6 的,需要另外安装.安装完 IIS 6,还需要单独开启对于 ASP 的支持. 第一步,启用Asp,进入:控制面板 ...

  4. Windows Server 2003 动态网站IIS设置(图)

    一.安装IIS     Windows Server 2003 虽说是服务器版本,但在默认情况下并没有安装IIS,要在本地浏览asp,PHP等动态网页,就必须安装IIS.在买系统盘的时候,请注意看一下 ...

  5. IIS隐藏版本号教程(Windows Server 2003)

    1.下载Urlscan https://www.microsoft.com/en-us/search/DownloadResults.aspx?q=URLScan(总下载页面) https://dow ...

  6. 用户收到"无法显示页面"的错误消息和"Connections_refused"条目记录在运行 Windows Server 2003,Exchange 2003 和 IIS 6.0 的服务器上的 Httperr.log 文件

    症状 您会遇到下列症状在运行 Microsoft Windows Server 2003. Microsoft Exchange Server 2003年和 Microsoft Internet In ...

  7. C# 创建iis站点以及IIS站点属性,iis不能启动站点

    DontLog = False是否将客户端的请求写入日志文件 2011年04月09日 #region CreateWebsite 新增网站 public string CreateWebSite(st ...

  8. 通过代码动态创建IIS站点

    对WebApi进行单元测试时,一般需要一个IIS站点,一般的做法,是通过写一个批处理的bat脚本来实现,其实通过编码,也能实现该功能. 主要有关注三点:应用程序池.Web站点.绑定(协议类型:http ...

  9. cmd 批处理创建 IIS 站点

    windows 创建站点命令 appcmd C:\Windows\System32\inetsrv\appcmd.exe SITE 虚拟站点的管理 APP 管理应用程序 VDIR 管理虚拟目录 APP ...

随机推荐

  1. 如何在招聘中考核.NET架构师

    .NET架构师招聘不如JAVA那么顺利,可以搜索到的.NET架构师可以说是凤毛菱角.当然好的架构师都是需要长期观察和挖角才能得手,如何去招聘到合适的.NET架构师可能是摆在所有求贤者面前的难题.这里的 ...

  2. Python-定时爬取指定城市天气(一)-发送给关心的微信好友

    一.背景 上班的日子总是3点一线,家里,公司和上班的路径,对于一个特别懒得我来说,经常遇到上班路上下雨了,而我却没带伞,多么痛的领悟.最近对python有一种狂热的学习热情,写了4年多的C++代码,对 ...

  3. RabbitMq在CentOs7下的完整安装步骤,带你踩坑

    1.前言 因为公司项目中用的RabbitMq来做消息处理,自己以前没有接触过,所以想自学一下.然额,光安装就花了6.7个小时才搞定,中间还换过一个版本,综合国内外博客才最终将所有安装中遇到的问题解决掉 ...

  4. 神经网络——反向传播BP算法公式推导

    在神经网络中,当我们的网络层数越来越多时,网络的参数也越来越多,如何对网络进行训练呢?我们需要一种强大的算法,无论网络多复杂,都能够有效的进行训练.在众多的训练算法中,其中最杰出的代表就是BP算法,它 ...

  5. 天津联通新兴ICT业务工程师面试经历

    此次是天津联通来我们学校进行校招宣讲,参加的人挺多的.一开始没打印成绩单,临时去打印的,然后排到我的时候以经快结束了 == 面试 首先当然是自我介绍啦,就巴拉巴拉了一堆自己的专业,学过什么跟职位相关的 ...

  6. USB总线标准

    1.USB总线类型: OHCI(Open Host Controller Interface)是支持USB1.1的标准,但它不仅仅是针对USB,UHCI(Universal Host Controll ...

  7. JAVA的特性

    JAVA有三大特性:封装,继承和多态 一. 封装 封装就是将类的信息隐藏在类内部,不允许外部程序直接访问,而是通过该类的方法实现对隐藏信息的操作和访问. 封装的实现 a. 需要修改属性的访问控制符(修 ...

  8. Linux下使用ntpdate进行时间同步

    转摘自Linux下使用ntpdate进行时间同步https://www.cnblogs.com/zhi-leaf/p/6281549.html1.安装ntpdate,执行以下命令 # yum inst ...

  9. 关于web资金系统提现安全保护,防止极快的重复并发请求导致重复提现的解决思路

    关于WEB金融系统中的提现安全问题很多人没有深入思想,导致有漏洞,常常会遇到有些人遇到被攻击到导资金损失的麻烦,     其实要彻底解决重复并发请求 导致重复提现问题,是需要花点心思的,并没有看起来的 ...

  10. 在keil中添加stc系列单片机型号(模型)方法

    1.下载安装stc-isp烧录软件: 官网:http://www.gxwmcu.com/ 2.打开使用stc-isp软件,并导入stc官方器件库: 注意:一定要找到包含有C51和UV4的文件夹 3.显 ...