`
wyf
  • 浏览: 424860 次
  • 性别: Icon_minigender_1
  • 来自: 唐山
社区版块
存档分类
最新评论

C#操作IIS(转)可以写一个工具自己配置网站

阅读更多
using System;
using System.DirectoryServices;
using System.Collections;
using System.Text.RegularExpressions;
using System.Text;
 
namespace Demo
{
     /// <summary>
     ///  这个类是静态类。用来实现管理IIS的基本操作。
     ///  管理IIS有两种方式,一是ADSI,一是WMI。由于系统限制的原因,只好选择使用ADSI实现功能。
     ///  这是一个遗憾。只有等到只有使用IIS 6的时候,才有可能使用WMI来管理系统
     ///  不过有一个问题就是,我现在也觉得这样的一个方法在本地执行会比较的好。最好不要远程执行。
     ///  因为那样需要占用相当数量的带宽,即使要远程执行,也是推荐在同一个网段里面执行
     /// </summary>
     public class IISAdminLib
     {
          #region UserName,Password,HostName的定义
         public static string HostName
         {
              get
              {
                   return hostName;
              }
              set
              {
                   hostName = value;
              }
         }
 
         public static string UserName
         {
              get
              {
                   return userName;
              }
              set
              {
                   userName = value;
              }
         }
 
         public static string Password
         {
              get
              {
                   return password;
              }
              set
              {
                   if(UserName.Length <= 1)
                   {
                       throw new ArgumentException("还没有指定好用户名。请先指定用户名");
                   }
 
                   password = value;
              }
         }
 
         public static void RemoteConfig(string hostName, string userName, string password)
         {
              HostName = hostName;
              UserName = userName;
              Password = password;
         }
 
          private static string hostName = "localhost";
          private static string userName;
          private static string password;
          #endregion
 
          #region 根据路径构造Entry的方法
         /// <summary>
         ///  根据是否有用户名来判断是否是远程服务器。
         ///  然后再构造出不同的DirectoryEntry出来
         /// </summary>
         /// <param name="entPath">DirectoryEntry的路径</param>
         /// <returns>返回的是DirectoryEntry实例</returns>
         public static DirectoryEntry GetDirectoryEntry(string entPath)
         {
              DirectoryEntry ent;
 
              if(UserName == null)
              {
                   ent = new DirectoryEntry(entPath);
              }
              else
              {
                   //    ent = new DirectoryEntry(entPath, HostName+"\\"+UserName, Password, AuthenticationTypes.Secure);
                   ent = new DirectoryEntry(entPath, UserName, Password, AuthenticationTypes.Secure);
              }
 
              return ent;
         }
          #endregion
 
          #region 添加,删除网站的方法
         /// <summary>
         ///  创建一个新的网站。根据传过来的信息进行配置
         /// </summary>
         /// <param name="siteInfo">存储的是新网站的信息</param>
         public static void CreateNewWebSite(NewWebSiteInfo siteInfo)
         {
              if(! EnsureNewSiteEnavaible(siteInfo.BindString))
              {
                   throw new DuplicatedWebSiteException("已经有了这样的网站了。" + Environment.NewLine + siteInfo.BindString);
              }
 
              string entPath = String.Format("IIS://{0}/w3svc", HostName);
              DirectoryEntry rootEntry = GetDirectoryEntry(entPath);
 
              string 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();
 
              vdEntry.Properties["Path"].Value = siteInfo.WebPath;
              vdEntry.CommitChanges();
         }
 
         /// <summary>
         ///  删除一个网站。根据网站名称删除。
         /// </summary>
         /// <param name="siteName">网站名称</param>
         public static void DeleteWebSiteByName(string siteName)
         {
              string siteNum = GetWebSiteNum(siteName);
              string siteEntPath = String.Format("IIS://{0}/w3svc/{1}", HostName, siteNum);
              DirectoryEntry siteEntry = GetDirectoryEntry(siteEntPath);
 
              string rootPath = String.Format("IIS://{0}/w3svc", HostName);
              DirectoryEntry rootEntry = GetDirectoryEntry(rootPath);
 
              rootEntry.Children.Remove(siteEntry);
              rootEntry.CommitChanges();
         }
          #endregion
 
          #region Start和Stop网站的方法
         public static void StartWebSite(string siteName)
         {
              string siteNum = GetWebSiteNum(siteName);
              string siteEntPath = String.Format("IIS://{0}/w3svc/{1}", HostName, siteNum);
              DirectoryEntry siteEntry = GetDirectoryEntry(siteEntPath);
 
              siteEntry.Invoke("Start", new object[] {});
         }
 
         public static void StopWebSite(string siteName)
         {
              string siteNum = GetWebSiteNum(siteName);
              string siteEntPath = String.Format("IIS://{0}/w3svc/{1}", HostName, siteNum);
              DirectoryEntry siteEntry = GetDirectoryEntry(siteEntPath);
 
              siteEntry.Invoke("Stop", new object[] {});
         }
          #endregion
 
          #region 确认网站是否相同
         /// <summary>
         ///  确定一个新的网站与现有的网站没有相同的。
         ///  这样防止将非法的数据存放到IIS里面去
         /// </summary>
         /// <param name="bindStr">网站邦定信息</param>
         /// <returns>真为可以创建,假为不可以创建</returns>
         public static bool EnsureNewSiteEnavaible(string bindStr)
         {
              string entPath = String.Format("IIS://{0}/w3svc", HostName);
              DirectoryEntry ent = GetDirectoryEntry(entPath);
  
              foreach(DirectoryEntry child in ent.Children)
              {
                   if(child.SchemaClassName == "IIsWebServer")
                   {
                        if(child.Properties["ServerBindings"].Value != null)
                       {
                            if(child.Properties["ServerBindings"].Value.ToString() == bindStr)
                            {
                                 return false;
                            }
                       }
                   }
              }
 
              return true;
         }
          #endregion
 
          #region 获取一个网站编号的方法
         /// <summary>
         ///  获取一个网站的编号。根据网站的ServerBindings或者ServerComment来确定网站编号
         /// </summary>
         /// <param name="siteName"></param>
         /// <returns>返回网站的编号</returns>
         /// <exception cref="NotFoundWebSiteException">表示没有找到网站</exception>
         public static string GetWebSiteNum(string siteName)
         {
              Regex regex = new Regex(siteName);
              string tmpStr;
 
              string entPath = String.Format("IIS://{0}/w3svc", HostName);
              DirectoryEntry ent = GetDirectoryEntry(entPath);
  
              foreach(DirectoryEntry child in ent.Children)
              {
                   if(child.SchemaClassName == "IIsWebServer")
                   {
                        if(child.Properties["ServerBindings"].Value != null)
                       {
                            tmpStr = child.Properties["ServerBindings"].Value.ToString();
                            if(regex.Match(tmpStr).Success)
                            {
                                 return child.Name;
                            }
                       }
 
                        if(child.Properties["ServerComment"].Value != null)
                       {
                            tmpStr = child.Properties["ServerComment"].Value.ToString();
                            if(regex.Match(tmpStr).Success)
                            {
                                 return child.Name;
                            }
                       }
                   }
              }
 
              throw new NotFoundWebSiteException("没有找到我们想要的站点" + siteName);
         }
          #endregion
 
          #region 获取新网站id的方法
         /// <summary>
         ///  获取网站系统里面可以使用的最小的ID。
         ///  这是因为每个网站都需要有一个唯一的编号,而且这个编号越小越好。
         ///  这里面的算法经过了测试是没有问题的。
         /// </summary>
         /// <returns>最小的id</returns>
         public static string GetNewWebSiteID()
         {
              ArrayList list = new ArrayList();
              string tmpStr;
 
              string entPath = String.Format("IIS://{0}/w3svc", HostName);
              DirectoryEntry ent = GetDirectoryEntry(entPath);
  
              foreach(DirectoryEntry child in ent.Children)
              {
                   if(child.SchemaClassName == "IIsWebServer")
                   {
                       tmpStr = child.Name.ToString();
                        list.Add(Convert.ToInt32(tmpStr));
                   }
              }
 
              list.Sort();
 
              int i = 1;
              foreach(int j in list)
              {
                   if(i == j)
                   {
                       i++;
                   }
              }
 
              return i.ToString();
         }
          #endregion
     }
 
     #region 新网站信息结构体
     public struct NewWebSiteInfo
     {
          private string hostIP;   // The Hosts IP Address
          private string portNum;   // The New Web Sites Port.generally is "80"
          private string descOfWebSite; // 网站表示。一般为网站的网站名。例如"www.dns.com.cn"
          private string commentOfWebSite;// 网站注释。一般也为网站的网站名。
          private string webPath;   // 网站的主目录。例如"e:\tmp"
 
         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);
              }
         }
 
         public string CommentOfWebSite
         {
              get
              {
                   return commentOfWebSite;
              }
         }
 
         public string WebPath
         {
              get
              {
                   return webPath;
              }
         }
     }
     #endregion
}

 

分享到:
评论

相关推荐

    Web网站IIS配置工具

    本工具适用于IIS6.0及以上版本。可配置.net环境,可附加SQL数据库,配置IIS,一键发布Web网站,并且,MVC架构的网站也能配置,附源码。

    C#解决IIS域名批量绑定

    由于业务需要,IIS要绑定几千个域名,如果通过界面手动绑定域名肯定是行不通的,于是写了个小工具来解决IIS批量绑定域名的问题。其实思路很简单,就是直接操作IIS的配置文件。

    C#部署数据库及IIS站点

    最近忙里偷闲,做了一个部署数据库及IIS网站站点的WPF应用程序工具。  二、内容 此工具的目的是: 根据.sql文件在本机上部署数据库 在本机部署IIS站点,包括新建站点,新建应用程序池。只新建而不会对本机上原有...

    本地IIS外网映射工具

    1.通过配置外网域名访问本地IIS地址。 2.适用于webapi接口调用与小型网站,功能与花生壳类似,支持穿透访问。 3.当前版本只支持get和post方法。只支持图片上传,不支持其它格式文件上传,上传最大10M。

    check_iis:用C#编写的插件,用于监视本地计算机上的IIS站点和AppPool

    要运行此功能,代理/执行程序服务必须以admin身份运行,由于要求admin具有更高的权限才能从IIS读取配置存储,因此用户权限还不够。 站点和应用程序池匹配项中的区分大小写。 仅使用命名的开关,单个字符的快捷...

    C#打包--如何用VS2005制作Web安装程序

    C#打包--如何用VS2005制作Web安装程序,网站完成后,需要部署到目标机器上,方法有很多,直接把文件Copy到目标机器上,执行SQL脚本,配置IIS,这样可以做到;也可以使用InstallShield这样到专业制作软件来打包。本篇...

    C# 开发webservice接口、请求HTTP接口、iis发布服务

    本例开发工具用的是Visual Studio 2022,C#开发,代码实现以下功能 ① webservice接口服务功能; ② 请求HTTP接口类(以下简称B接口,C接口); ③ 访问oracle数据库类; ④ 写日志类; ⑤ 无入参方法; ⑥ 带入参方法...

    c#客户端程序自动更新工具(含源码)

    1、配置好更新文件的web服务器,例如IIS服务器。 注意:要配置好服务器所能支持的文件下载类型,即MIME类型,否则下载时会出错。 假设下载地址为http://www.xxxxx.com 自动生成的程序和文件默认版本号均为1.0.0.0,...

    KerberosConfigMgrIIS:IIS的Kerberos配置管理器

    我们许多人发现对Kerberos进行故障排除是一项繁琐的任务,因为它涉及多个级别的故障排除。 今天,为了在IIS服务器上配置kerberos,我们需要完成一系列步骤,这确实很耗时并且非常复杂。 为什么Kerberos有时会很痛苦...

    C#+PaddleOCRSharp 实现深度学习识别字符

     PaddleOCRSharp是基于PaddleOCR的C++代码修改并封装的.NET工具类库,支持文本识别、文本检测、基于文本检测结果的统计分析的表格识别功能。

    C#在线考试系统 vs2005+sqlserver2005

    (1)依次选择“开始”/“设置”/“控制面板”/“管理工具”/“Internet信息服务(IIS)管理器”选项,弹出“Internet信息服务(IIS)管理器”窗口,如图1.1所示。 图1.1 “Internet信息服务(IIS)管理器”窗口 (2)...

    中美 IT 培训 C# Asp.net 笔记3

    (120课时) 在培训老师的指导下完成一个实际的电子商务软件项目:” Prepaid Phone Card Online Sales System”。内容包括:Application Architecture Analysis、Creating the Data Model、Design Database Schema、...

    FTP服务器的架设.txt

    FTP服务器在文件的传输上性能稳定,占用系统资源小,而且传输速度快,现在网上已经有很多的FTP服务器可供使用,而自己架设一个FTP服务器也很容易,下面介绍两种主流的FTP架构方式。 1.利用微软公司的IIS 微软的IIS...

    c#在线投票

    &lt;br&gt;2、配置IIS (1)打开“开始”→“控制面板”命令,打开“控制面板”窗口,在该窗口中双击“管理工具”图标,进入到“管理工具”窗口,在该窗口中双击“Internet 信息服务”图标,运行“Internet 信息...

    IISServerManager

    C#项目,管理IIS7,核心程序生成一个dll,可以调用这个dll来创建网站,创建应用程序池,创建虚拟目录,配置系统目录权限等等;另外此项目还包含一个winform程序;用来测试生成的dll的正确性。

    C#2008宝典光盘

    服务器操作系统:开发过程中使用Windows XP Professional操作系统,系统运行服务器可以采用Windows 2000 Professional、Windows 2000 Server或其他操作系统。 -----------------------------硬件环境-------------...

    C#图书馆管理系统 vs2005+sqlserv er2005

    (1)依次选择“开始”/“设置”/“控制面板”/“管理工具”/“Internet信息服务(IIS)管理器”选项,弹出“Internet信息服务(IIS)管理器”窗口,如图1.5所示。 图1.5 “Internet信息服务(IIS)管理器”窗口 (2)...

    JobScheduleDemoCode-master

    1、这个项目完全使用啦cron-like表达式实现触发器配置,如果你对cron不了解,那么我上篇中有针对cron做介绍讲解,如果你对cron了解而没有一个合适的生成工具,那么入左上方2个群,找我。 2、这个项目部署在IIS中,...

    中美 IT 培训 C# Asp.net 笔记2

    (120课时) 在培训老师的指导下完成一个实际的电子商务软件项目:” Prepaid Phone Card Online Sales System”。内容包括:Application Architecture Analysis、Creating the Data Model、Design Database Schema、...

    中美 IT 培训 C# Asp.net 全套笔记1

    (120课时) 在培训老师的指导下完成一个实际的电子商务软件项目:” Prepaid Phone Card Online Sales System”。内容包括:Application Architecture Analysis、Creating the Data Model、Design Database Schema、...

Global site tag (gtag.js) - Google Analytics