设为首页 收藏本站
查看: 921|回复: 0

[经验分享] C#操作IIS程序池及站点的创建配置实现代码

[复制链接]

尚未签到

发表于 2015-11-15 01:37:33 | 显示全部楼层 |阅读模式
最近在做一个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=&quot;AppPoolName&quot;>程序池名称</param>
        /// <returns>true存在 false不存在</returns>
        private bool IsAppPoolName(string AppPoolName)
        {
            bool result = false;
            DirectoryEntry appPools = new DirectoryEntry(&quot;IIS://localhost/W3SVC/AppPools&quot;);
            foreach (DirectoryEntry getdir in appPools.Children)
            {
                if (getdir.Name.Equals(AppPoolName))
                {
                    result = true;
                }
            }
            return result;
        }
  
  3:删除应用程序池
  
复制代码 代码如下:
/// <summary>
        /// 删除指定程序池
        /// </summary>
        /// <param name=&quot;AppPoolName&quot;>程序池名称</param>
        /// <returns>true删除成功 false删除失败</returns>
        private bool DeleteAppPool(string AppPoolName)
        {
            bool result = false;
            DirectoryEntry appPools = new DirectoryEntry(&quot;IIS://localhost/W3SVC/AppPools&quot;);
            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 = &quot;LamAppPool&quot;;
            if (!IsAppPoolName(AppPoolName))
            {
                DirectoryEntry newpool;
                DirectoryEntry appPools = new DirectoryEntry(&quot;IIS://localhost/W3SVC/AppPools&quot;);
                newpool = appPools.Children.Add(AppPoolName, &quot;IIsApplicationPool&quot;);
                newpool.CommitChanges();
                MessageBox.Show(AppPoolName &#43; &quot;程序池增加成功&quot;);
            }
            #endregion  
  #region 修改应用程序的配置(包含托管模式及其NET运行版本)
            ServerManager sm = new ServerManager();
            sm.ApplicationPools[AppPoolName].ManagedRuntimeVersion = &quot;v4.0&quot;;
            sm.ApplicationPools[AppPoolName].ManagedPipelineMode = ManagedPipelineMode.Classic; //托管模式Integrated为集成 Classic为经典
            sm.CommitChanges();
            MessageBox.Show(AppPoolName &#43; &quot;程序池托管管道模式:&quot; &#43; sm.ApplicationPools[AppPoolName].ManagedPipelineMode.ToString() &#43; &quot;运行的NET版本为:&quot; &#43; 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(&quot;windir&quot;) &#43; @&quot;\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe&quot;;
            ProcessStartInfo startInfo = new ProcessStartInfo(fileName);
            //处理目录路径
            string path = vdEntry.Path.ToUpper();
            int index = path.IndexOf(&quot;W3SVC&quot;);
            path = path.Remove(0, index);
            //启动ASPnet_iis.exe程序,刷新脚本映射
            startInfo.Arguments = &quot;-s &quot; &#43; 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 = &quot;.xaml&quot;; NewMime.MimeType = &quot;application/xaml&#43;xml&quot;;
            IISOle.MimeMapClass TwoMime = new IISOle.MimeMapClass();
            TwoMime.Extension = &quot;.xap&quot;; TwoMime.MimeType = &quot;application/x-silverlight-app&quot;;
            rootEntry.Properties[&quot;MimeMap&quot;].Add(NewMime);
            rootEntry.Properties[&quot;MimeMap&quot;].Add(TwoMime);
            rootEntry.CommitChanges();
  
  7:下面是做安装时一段对IIS进行操作的代码;兼容IIS6及IIS7;新建虚拟目录并对相应的属性进行设置;对IIS7还进行新建程序池的程序;并设置程序池的配置;
  
复制代码 代码如下:
/// <summary>
    /// 创建网站
    /// </summary>
    /// <param name=&quot;siteInfo&quot;></param>
      public  void CreateNewWebSite(NewWebSiteInfo siteInfo)
        {
            if (!EnsureNewSiteEnavaible(siteInfo.BindString))
            {
                throw new Exception(&quot;该网站已存在&quot; &#43; Environment.NewLine &#43; siteInfo.BindString);
            }
            DirectoryEntry rootEntry = GetDirectoryEntry(entPath);  
  newSiteNum = GetNewWebSiteID();
            DirectoryEntry newSiteEntry = rootEntry.Children.Add(newSiteNum, &quot;IIsWebServer&quot;);
            newSiteEntry.CommitChanges();
  newSiteEntry.Properties[&quot;ServerBindings&quot;].Value = siteInfo.BindString;
            newSiteEntry.Properties[&quot;ServerComment&quot;].Value = siteInfo.CommentOfWebSite;
            newSiteEntry.CommitChanges();
            DirectoryEntry vdEntry = newSiteEntry.Children.Add(&quot;root&quot;, &quot;IIsWebVirtualDir&quot;);
            vdEntry.CommitChanges();
            string ChangWebPath = siteInfo.WebPath.Trim().Remove(siteInfo.WebPath.Trim().LastIndexOf('\\'),1);
            vdEntry.Properties[&quot;Path&quot;].Value = ChangWebPath;
  
            vdEntry.Invoke(&quot;AppCreate&quot;, true);//创建应用程序
  vdEntry.Properties[&quot;AccessRead&quot;][0] = true; //设置读取权限
            vdEntry.Properties[&quot;AccessWrite&quot;][0] = true;
            vdEntry.Properties[&quot;AccessScript&quot;][0] = true;//执行权限
            vdEntry.Properties[&quot;AccessExecute&quot;][0] = false;
            vdEntry.Properties[&quot;DefaultDoc&quot;][0] = &quot;Login.aspx&quot;;//设置默认文档
            vdEntry.Properties[&quot;AppFriendlyName&quot;][0] = &quot;LabManager&quot;; //应用程序名称         
            vdEntry.Properties[&quot;AuthFlags&quot;][0] = 1;//0表示不允许匿名访问,1表示就可以3为基本身份验证,7为windows继承身份验证
            vdEntry.CommitChanges();
  //操作增加MIME
            //IISOle.MimeMapClass NewMime = new IISOle.MimeMapClass();
            //NewMime.Extension = &quot;.xaml&quot;; NewMime.MimeType = &quot;application/xaml&#43;xml&quot;;
            //IISOle.MimeMapClass TwoMime = new IISOle.MimeMapClass();
            //TwoMime.Extension = &quot;.xap&quot;; TwoMime.MimeType = &quot;application/x-silverlight-app&quot;;
            //rootEntry.Properties[&quot;MimeMap&quot;].Add(NewMime);
            //rootEntry.Properties[&quot;MimeMap&quot;].Add(TwoMime);
            //rootEntry.CommitChanges();
  #region 针对IIS7
            DirectoryEntry getEntity = new DirectoryEntry(&quot;IIS://localhost/W3SVC/INFO&quot;);
            int Version =int.Parse(getEntity.Properties[&quot;MajorIISVersionNumber&quot;].Value.ToString());
            if (Version > 6)
            {
                #region 创建应用程序池
                string AppPoolName = &quot;LabManager&quot;;
                if (!IsAppPoolName(AppPoolName))
                {
                    DirectoryEntry newpool;
                    DirectoryEntry appPools = new DirectoryEntry(&quot;IIS://localhost/W3SVC/AppPools&quot;);
                    newpool = appPools.Children.Add(AppPoolName, &quot;IIsApplicationPool&quot;);
                    newpool.CommitChanges();
                }
                #endregion
  #region 修改应用程序的配置(包含托管模式及其NET运行版本)
                ServerManager sm = new ServerManager();
                sm.ApplicationPools[AppPoolName].ManagedRuntimeVersion = &quot;v4.0&quot;;
                sm.ApplicationPools[AppPoolName].ManagedPipelineMode = ManagedPipelineMode.Classic; //托管模式Integrated为集成 Classic为经典
                sm.CommitChanges();
                #endregion
  vdEntry.Properties[&quot;AppPoolId&quot;].Value = AppPoolName;
                vdEntry.CommitChanges();
            }
            #endregion
  
            //启动aspnet_regiis.exe程序
            string fileName = Environment.GetEnvironmentVariable(&quot;windir&quot;) &#43; @&quot;\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe&quot;;
            ProcessStartInfo startInfo = new ProcessStartInfo(fileName);
            //处理目录路径
            string path = vdEntry.Path.ToUpper();
            int index = path.IndexOf(&quot;W3SVC&quot;);
            path = path.Remove(0, index);
            //启动ASPnet_iis.exe程序,刷新脚本映射
            startInfo.Arguments = &quot;-s &quot; &#43; 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(&quot;IIS://{0}/w3svc&quot;, &quot;localhost&quot;);  
  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; // 网站表示。一般为网站的网站名。例如&quot;www.dns.com.cn&quot;
            private string commentOfWebSite;// 网站注释。一般也为网站的网站名。
            private string webPath;   // 网站的主目录。例如&quot;e:\ mp&quot;
  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(&quot;{0}:{1}:{2}&quot;, hostIP, portNum, descOfWebSite); //网站标识(IP,端口,主机头&#20540;)
                }
            }
  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=&quot;FileAdd&quot;>文件夹路径</param>
        public void SetFileRole()
        {
            string FileAdd = this.Context.Parameters[&quot;installdir&quot;].ToString();
            FileAdd = FileAdd.Remove(FileAdd.LastIndexOf('\\'), 1);
            DirectorySecurity fSec = new DirectorySecurity();
            fSec.AddAccessRule(new FileSystemAccessRule(&quot;Everyone&quot;,FileSystemRights.FullControl,InheritanceFlags.ContainerInherit|InheritanceFlags.ObjectInherit,PropagationFlags.None,AccessControlType.Allow));
            System.IO.Directory.SetAccessControl(FileAdd, fSec);
        }

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-139305-1-1.html 上篇帖子: IIS下的URL重写无效问题 下篇帖子: IIS7下web.config奇葩的问题。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表