• 测试项目结构:

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. privoxy自动请求转发到多个网络

    有些时候我们需要通过不同的代理访问不同资源,比如某些ip或域名走本地网络,某些ip或域名走不可描述的代理等.当然这只是举个栗子! 我要解决的问题是:我的内网机器没有internet访问权限,但是我的应 ...

  2. 列举Java中常用的包、类和接口

    常用的类: BufferedReader ,BufferedWriter FileReader    ,FileWirter String      ,Integer Date        ,Cla ...

  3. Windows上安装配置SSH教程(8)——综合应用:在Windows上使用手动方式实现SSH远程登陆与文件传输

    服务器端操作系统:Windows XP 客户端操作系统:Windows10 安装与配置顺序 1.服务端安装OpenSSH 2.服务端配置OpenSSH 3.客户端安装OpenSSH 4.客户端安装Wi ...

  4. React Native开发 - 搭建React Native开发环境

    移动开发以前一般都是原生的语言来开发,Android开发是用Java语言,IOS的开发是Object-C或者Swift.那么对于开发一个App,至少需要两套代码.两个团队.对于公司来说,成本还是有的. ...

  5. MIP 脚本域名地址变更公告

    尊敬的 MIP 开发者: MIP 团队为了解决 MIP-Cache 页面下 cookie 相互覆盖问题,增强站点品牌露出,在 2017 年 8 月将 MIP 的脚本域名和 MIP-Cache 页面域名 ...

  6. css节点选择器

    基础选择器 基础选择器是选择器的所有选择器的基本组成元素,也最简单,包含如下5个类别: ID选择器 标签选择器 类选择器 属性选择器:类选择器算是一个特殊的属性选择器,通用的属性选择器举例如下: #c ...

  7. zookeeper源码 — 一、单机启动

    zookeeper一般使用命令工具启动,启动主要就是初始化所有组件,让server可以接收并处理来自client的请求.本文主要结构: main入口 配置解析 组件启动 main入口 我们一般使用命令 ...

  8. Java之Spring mvc详解

    文章大纲 一.Spring mvc介绍二.Spring mvc代码实战三.项目源码下载四.参考文章   一.Spring mvc介绍 1. 什么是springmvc   springmvc是sprin ...

  9. MSSQL 更改表结构

    更改表结构: alter TABLE 表1 ALTER COLUMN 列名1 NCHAR(40)

  10. Windows Server 2016-OU组织单位日常操作

    技术无所谓贵贱,既然曾经做过就总该是要留下点什么,毕竟做技术这些年给我们留下太多太多的成长经历,总有人问这些已经很皮毛了为什么还要写,其实没那么多花哨理由,就是想着做或者不做这一块总是要对过往做个简单 ...