C#操作IIS程序池及站点的创建配置实现代码

 更新时间:2013年03月29日 16:24:32   作者:  
最近在做一个WEB程序的安装包;对一些操作IIS进行一个简单的总结;主要包括对IIS进行站点的新建以及新建站点的NET版本的选择,还有针对IIS7程序池的托管模式以及版本的操作

首先要对Microsoft.Web.Administration进行引用,它主要是用来操作IIS7;

using System.DirectoryServices;
using Microsoft.Web.Administration;

1:首先是对本版IIS的版本进行配置:

复制代码 代码如下:

DirectoryEntry getEntity = new DirectoryEntry("IIS://localhost/W3SVC/INFO");
            string Version = getEntity.Properties["MajorIISVersionNumber"].Value.ToString();
            MessageBox.Show("IIS版本为:" + Version);

2:是判断程序池是存在;

复制代码 代码如下:

/// <summary>
        /// 判断程序池是否存在
        /// </summary>
        /// <param name="AppPoolName">程序池名称</param>
        /// <returns>true存在 false不存在</returns>
        private bool IsAppPoolName(string AppPoolName)
        {
            bool result = false;
            DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
            foreach (DirectoryEntry getdir in appPools.Children)
            {
                if (getdir.Name.Equals(AppPoolName))
                {
                    result = true;
                }
            }
            return result;
        }

3:删除应用程序池

复制代码 代码如下:

/// <summary>
        /// 删除指定程序池
        /// </summary>
        /// <param name="AppPoolName">程序池名称</param>
        /// <returns>true删除成功 false删除失败</returns>
        private bool DeleteAppPool(string AppPoolName)
        {
            bool result = false;
            DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
            foreach (DirectoryEntry getdir in appPools.Children)
            {
                if (getdir.Name.Equals(AppPoolName))
                {
                    try
                    {
                        getdir.DeleteTree();
                        result = true;
                    }
                    catch
                    {
                        result = false;
                    }
                }
            }
            return result;
        }

4:创建应用程序池 (对程序池的设置主要是针对IIS7;IIS7应用程序池托管模式主要包括集成跟经典模式,并进行NET版本的设置)

复制代码 代码如下:

string AppPoolName = "LamAppPool";
            if (!IsAppPoolName(AppPoolName))
            {
                DirectoryEntry newpool;
                DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
                newpool = appPools.Children.Add(AppPoolName, "IIsApplicationPool");
                newpool.CommitChanges();
                MessageBox.Show(AppPoolName + "程序池增加成功");
            }
            #endregion

            #region 修改应用程序的配置(包含托管模式及其NET运行版本)
            ServerManager sm = new ServerManager();
            sm.ApplicationPools[AppPoolName].ManagedRuntimeVersion = "v4.0";
            sm.ApplicationPools[AppPoolName].ManagedPipelineMode = ManagedPipelineMode.Classic; //托管模式Integrated为集成 Classic为经典
            sm.CommitChanges();
            MessageBox.Show(AppPoolName + "程序池托管管道模式:" + sm.ApplicationPools[AppPoolName].ManagedPipelineMode.ToString() + "运行的NET版本为:" + sm.ApplicationPools[AppPoolName].ManagedRuntimeVersion);

运用C#代码来对IIS7程序池托管管道模式及版本进行修改;



5:针对IIS6的NET版进行设置;因为此处我是用到NET4.0所以V4.0.30319 若是NET2.0则在这进行修改 v2.0.50727

复制代码 代码如下:

//启动aspnet_regiis.exe程序
            string fileName = Environment.GetEnvironmentVariable("windir") + @"\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe";
            ProcessStartInfo startInfo = new ProcessStartInfo(fileName);
            //处理目录路径
            string path = vdEntry.Path.ToUpper();
            int index = path.IndexOf("W3SVC");
            path = path.Remove(0, index);
            //启动ASPnet_iis.exe程序,刷新脚本映射
            startInfo.Arguments = "-s " + path;
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            Process process = new Process();
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit();
            string errors = process.StandardError.ReadToEnd();

6:平常我们可能还得对IIS中的MIME类型进行增加;下面主要是我们用到两个类型分别是:xaml,xap

复制代码 代码如下:

IISOle.MimeMapClass NewMime = new IISOle.MimeMapClass();
            NewMime.Extension = ".xaml"; NewMime.MimeType = "application/xaml+xml";
            IISOle.MimeMapClass TwoMime = new IISOle.MimeMapClass();
            TwoMime.Extension = ".xap"; TwoMime.MimeType = "application/x-silverlight-app";
            rootEntry.Properties["MimeMap"].Add(NewMime);
            rootEntry.Properties["MimeMap"].Add(TwoMime);
            rootEntry.CommitChanges();

7:下面是做安装时一段对IIS进行操作的代码;兼容IIS6及IIS7;新建虚拟目录并对相应的属性进行设置;对IIS7还进行新建程序池的程序;并设置程序池的配置;

复制代码 代码如下:

/// <summary>
    /// 创建网站
    /// </summary>
    /// <param name="siteInfo"></param>
      public  void CreateNewWebSite(NewWebSiteInfo siteInfo)
        {
            if (!EnsureNewSiteEnavaible(siteInfo.BindString))
            {
                throw new Exception("该网站已存在" + Environment.NewLine + siteInfo.BindString);
            }
            DirectoryEntry rootEntry = GetDirectoryEntry(entPath);

            newSiteNum = GetNewWebSiteID();
            DirectoryEntry newSiteEntry = rootEntry.Children.Add(newSiteNum, "IIsWebServer");
            newSiteEntry.CommitChanges();

            newSiteEntry.Properties["ServerBindings"].Value = siteInfo.BindString;
            newSiteEntry.Properties["ServerComment"].Value = siteInfo.CommentOfWebSite;
            newSiteEntry.CommitChanges();
            DirectoryEntry vdEntry = newSiteEntry.Children.Add("root", "IIsWebVirtualDir");
            vdEntry.CommitChanges();
            string ChangWebPath = siteInfo.WebPath.Trim().Remove(siteInfo.WebPath.Trim().LastIndexOf('\\'),1);
            vdEntry.Properties["Path"].Value = ChangWebPath;


            vdEntry.Invoke("AppCreate", true);//创建应用程序

            vdEntry.Properties["AccessRead"][0] = true; //设置读取权限
            vdEntry.Properties["AccessWrite"][0] = true;
            vdEntry.Properties["AccessScript"][0] = true;//执行权限
            vdEntry.Properties["AccessExecute"][0] = false;
            vdEntry.Properties["DefaultDoc"][0] = "Login.aspx";//设置默认文档
            vdEntry.Properties["AppFriendlyName"][0] = "LabManager"; //应用程序名称          
            vdEntry.Properties["AuthFlags"][0] = 1;//0表示不允许匿名访问,1表示就可以3为基本身份验证,7为windows继承身份验证
            vdEntry.CommitChanges();

            //操作增加MIME
            //IISOle.MimeMapClass NewMime = new IISOle.MimeMapClass();
            //NewMime.Extension = ".xaml"; NewMime.MimeType = "application/xaml+xml";
            //IISOle.MimeMapClass TwoMime = new IISOle.MimeMapClass();
            //TwoMime.Extension = ".xap"; TwoMime.MimeType = "application/x-silverlight-app";
            //rootEntry.Properties["MimeMap"].Add(NewMime);
            //rootEntry.Properties["MimeMap"].Add(TwoMime);
            //rootEntry.CommitChanges();

            #region 针对IIS7
            DirectoryEntry getEntity = new DirectoryEntry("IIS://localhost/W3SVC/INFO");
            int Version =int.Parse(getEntity.Properties["MajorIISVersionNumber"].Value.ToString());
            if (Version > 6)
            {
                #region 创建应用程序池
                string AppPoolName = "LabManager";
                if (!IsAppPoolName(AppPoolName))
                {
                    DirectoryEntry newpool;
                    DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
                    newpool = appPools.Children.Add(AppPoolName, "IIsApplicationPool");
                    newpool.CommitChanges();
                }
                #endregion

                #region 修改应用程序的配置(包含托管模式及其NET运行版本)
                ServerManager sm = new ServerManager();
                sm.ApplicationPools[AppPoolName].ManagedRuntimeVersion = "v4.0";
                sm.ApplicationPools[AppPoolName].ManagedPipelineMode = ManagedPipelineMode.Classic; //托管模式Integrated为集成 Classic为经典
                sm.CommitChanges();
                #endregion

                vdEntry.Properties["AppPoolId"].Value = AppPoolName;
                vdEntry.CommitChanges();
            }
            #endregion


            //启动aspnet_regiis.exe程序
            string fileName = Environment.GetEnvironmentVariable("windir") + @"\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe";
            ProcessStartInfo startInfo = new ProcessStartInfo(fileName);
            //处理目录路径
            string path = vdEntry.Path.ToUpper();
            int index = path.IndexOf("W3SVC");
            path = path.Remove(0, index);
            //启动ASPnet_iis.exe程序,刷新脚本映射
            startInfo.Arguments = "-s " + path;
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            Process process = new Process();
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit();
            string errors = process.StandardError.ReadToEnd();
            if (errors != string.Empty)
            {
                throw new Exception(errors);
            }

        }

复制代码 代码如下:

string entPath = String.Format("IIS://{0}/w3svc", "localhost");

public  DirectoryEntry GetDirectoryEntry(string entPath)
       {
           DirectoryEntry ent = new DirectoryEntry(entPath);
           return ent;
       }

        public class NewWebSiteInfo
        {
            private string hostIP;   // 主机IP
            private string portNum;   // 网站端口号
            private string descOfWebSite; // 网站表示。一般为网站的网站名。例如"www.dns.com.cn"
            private string commentOfWebSite;// 网站注释。一般也为网站的网站名。
            private string webPath;   // 网站的主目录。例如"e:\ mp"

            public NewWebSiteInfo(string hostIP, string portNum, string descOfWebSite, string commentOfWebSite, string webPath)
            {
                this.hostIP = hostIP;
                this.portNum = portNum;
                this.descOfWebSite = descOfWebSite;
                this.commentOfWebSite = commentOfWebSite;
                this.webPath = webPath;
            }

            public string BindString
            {
                get
                {
                    return String.Format("{0}:{1}:{2}", hostIP, portNum, descOfWebSite); //网站标识(IP,端口,主机头值)
                }
            }

            public string PortNum
            {
                get
                {
                    return portNum;
                }
            }

            public string CommentOfWebSite
            {
                get
                {
                    return commentOfWebSite;
                }
            }

            public string WebPath
            {
                get
                {
                    return webPath;
                }
            }
        }

8:下面的代码是对文件夹权限进行设置,下面代码是创建Everyone 并给予全部权限

复制代码 代码如下:

/// <summary>
        /// 设置文件夹权限 处理给EVERONE赋予所有权限
        /// </summary>
        /// <param name="FileAdd">文件夹路径</param>
        public void SetFileRole()
        {
            string FileAdd = this.Context.Parameters["installdir"].ToString();
            FileAdd = FileAdd.Remove(FileAdd.LastIndexOf('\\'), 1);
            DirectorySecurity fSec = new DirectorySecurity();
            fSec.AddAccessRule(new FileSystemAccessRule("Everyone",FileSystemRights.FullControl,InheritanceFlags.ContainerInherit|InheritanceFlags.ObjectInherit,PropagationFlags.None,AccessControlType.Allow));
            System.IO.Directory.SetAccessControl(FileAdd, fSec);
        }

相关文章

  • OpenCvSharp图像的修改和保存以及掩膜操作

    OpenCvSharp图像的修改和保存以及掩膜操作

    这篇文章主要介绍了OpenCvSharp图像的修改和保存以及掩膜操作,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • C#实现农历日历的方法

    C#实现农历日历的方法

    这篇文章主要介绍了C#实现农历日历的方法,详细分析了使用C#实现农历日历的完整步骤,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-01-01
  • C#开发中的垃圾回收机制简析

    C#开发中的垃圾回收机制简析

    这篇文章主要为大家详细介绍了C#开发中的垃圾回收机制,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2015-10-10
  • C#对Xamarin框架进行数据绑定

    C#对Xamarin框架进行数据绑定

    这篇文章介绍了C#对Xamarin框架进行数据绑定,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-01-01
  • C# 泛型的简单理解(安全、集合、方法、约束、继承)分享

    C# 泛型的简单理解(安全、集合、方法、约束、继承)分享

    这篇文章介绍了C# 泛型的简单理解(安全、集合、方法、约束、继承),有需要的朋友可以参考一下
    2013-10-10
  • 基于C#实现语音识别功能详解

    基于C#实现语音识别功能详解

    在.NET4.0中,可以借助System.Speech组件让电脑来识别我们的声音。本文将利用该组件实现语音识别功能,文中实现过程讲解详细,需要的可以参考一下
    2022-04-04
  • 基于C#的电视台节目表接口调用代码

    基于C#的电视台节目表接口调用代码

    这篇文章主要介绍了基于C#的电视台节目表接口调用代码的相关资料,需要的朋友可以参考下
    2016-06-06
  • 基于Unity3D实现3D迷宫小游戏的示例代码

    基于Unity3D实现3D迷宫小游戏的示例代码

    迷宫游戏作为经典的小游戏,一直深受大家的喜爱。本文小编将为大家详细介绍一下如何用Unity实现一个3D版的迷宫小游戏,感兴趣的可以动手试一试
    2022-03-03
  • C#图形编程GDI+基础介绍

    C#图形编程GDI+基础介绍

    这篇文章介绍了C#中的图形编程GDI+,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-02-02
  • C#创建二叉搜索树的方法

    C#创建二叉搜索树的方法

    这篇文章主要介绍了C#创建二叉搜索树的方法,涉及C#二叉搜索树的实现技巧,非常具有实用价值,需要的朋友可以参考下
    2015-04-04

最新评论