C#创建IIS站点及相应的应用程序池,支持IIS6.0+Windows Server 2003. 使用Builder设计模式

时间:2019-03-21
本文章向大家介绍C#创建IIS站点及相应的应用程序池,支持IIS6.0+Windows Server 2003. 使用Builder设计模式,主要包括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("10");
                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", "0");
                //WebServerTypes ver = WebServerTypes.Unknown;
                System.Version ver = new Version();
                int major = 0;
                int minor = 0;
                if (obj != null)
                {
                    major = Convert.ToInt32(obj);
                }
                obj = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters", "MinorVersion", "0");
                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 == 5 && Environment.OSVersion.Version.Minor == 2;
            ////创建应用程序池
            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"][0] = "65535";
                //禁用回收 回收>>>固定时间间隔
                newAppPool.Properties["PeriodicRestartTime"][0] = "0";
                //闲置超时
                newAppPool.Properties["IdleTimeout"][0] = "0";

                newAppPool.Properties["AppPoolIdentityType"][0] = "2";
                if (!isWindowsServer2003)//windows server2003
                {
                    newAppPool.Properties["ManagedRuntimeVersion"][0] = "v4.0";//Net版本号//windows server2003不支持
                    newAppPool.Properties["ManagedPipelineMode"][0] = "0";//0:集成模式 1:经典模式windows server2003不支持
                    newAppPool.Properties["Enable32BitAppOnWin64"][0] = 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(0, path);//插入到IIS
            myde.Invoke("AppCreate", true);//创建
            myde.Properties["AppPoolId"][0] = appName;
            myde.Properties["AuthAnonymous"][0] = true;//允许匿名访问 
            myde.Properties["AccessRead"][0] = true; //开启读取
            myde.Properties["AccessScript"][0] = true;//脚本可执行
                                                      //设置是否禁用日志 默认为false。
            myde.Properties["DontLog"][0] = 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 = 65535;
                    //禁用回收 回收>>>固定时间间隔
                    pool.Recycling.PeriodicRestart.Time = new TimeSpan(0);
                    //闲置超时
                    pool.ProcessModel.IdleTimeout = new TimeSpan(0);
                    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">128</param>
        /// <returns></returns>

        public static string GetWindowsDirectory()
        {
            int count = 128;
            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 == 5 && Environment.OSVersion.Version.Minor == 2;
            if (isWindowsServer2003)
            {
                builderStr = "IIS6UtilsBuilder";
            }
            else
            {
                if (IISUtilsBuilder.IISVersion.Major < 7)
                {
                    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);
        }
    }
}
  • 运行结果