日期:2015-03-14  浏览次数:53374 次

前一段时间需要写一个小工具用于创建虚拟目录和设置注册表项,现在总结一下。有两种方式操作IIS:System.DirectoryServices空间下面的类,用于IIS5/6版本,和可以兼容iis6的IIS7版本;Microsoft.Web.Administration空间下面的类,IIS7引入的新的管理类。

1.使用System.DirectoryServices操作IIS.

《1》创建新站点

            string endPath = "IIS://localhost/W3SVC";   //注意字符串的最后没有/,否则将弹出异常<br>            DirectoryEntry dEntry=new DirectoryEntry(endPath); <br>            //创建一个站点<br>            int index = 0;<br>            foreach (DirectoryEntry item in dEntry.Children)<br>            {<br>                if(item.SchemaClassName=="IIsWebServer") //用于查找是否指定名称的website已存在               
{
                    if (item.Properties["ServerComment"][0].ToString() == "testCreate")//DirectoryEntry(IIsWebServer)的ServerComment属性指出站点的实际名称<br>                    {<br>                       dEntry.Children.Remove(item);//删除已经存在的站点<br>                       break;<br>                    }<br>                    if (int.Parse(item.Name) > index)  //DirectoryEntry(IIsWebServer0的Name属性表示的是一个int,IIS默认从1开始<br>                    {<br>                        index = int.Parse(item.Name);<br>                    }<br>                }<br>            }<br>            index++;<br>            DirectoryEntry newWebSite = null;<br>            newWebSite = dEntry.Children.Add(index.ToString(), "IIsWebServer");  //注意第二个参数<br>            newWebSite.Properties["ServerComment"][0] = "testCreate";      //设置站点名称<br>            newWebSite.Properties["ServerBindings"].Add("192.168.0.1:8080:");//设置站点的地址及端口号
newWebSite.Invoke("Put","ServerState",2);//设置网站已启动状态<br>            newWebSite.CommitChanges();

  这个过程称为绑定,构造函数中的路径有一定的格式:

IIS://服务器名/操作的服务目录/站点标示/目录名称               --用于特定应用下目录
IIS://服务器名/操作的服务目录                              --得到IIS目录服务

  IIS://localhost/w3svc,表示IIS服务。它下面都有什么对象呢?IIsFilters,IIsApplicationPools,IIsWebInfo,IIsWebServer,它们都是DirectoryEntry.SchemalClassName的值。其中IIsWebServer表示站点目录。那么一个站点目录又包含哪些对象呢?IIsWebVirtualDir(Root),IIsFilters(FILTERS),IIsCertMapper(IIsCertMapper),IIsCertMapper(CERT11S),它们也同样是DirectoryEntry.SchemalClassName的值,()中的值是DirectoryEntry.Name的值。

IIS服务用于管理站点,提供了ADSI(活动目录服务接口)。类似的还有LDAP服务,IIS服务和WinNT等等。

      服务器名可以是固定的IP,也可以是计算机名。这里使用的是本地(localhost)。

      W3SVC表示操作的是Web目录。

     通过这一步,我们创建了IIS服务对象s

《2》为新站点创建主目录,每一个站点都要有一个主目录。

   //为新建的webSite创建根目录root<br>            DirectoryEntry root = newWebSite.Children.Add("Root", "IIsWebVirtualDir"); 注意第二个参数<br>            root.Properties["Path"][0] = @"C:\11111";<br>            root.Properties["AuthAnonymous"][0] = true;  //允许匿名访问<br>            root.Properties["AccessScript"][0] = true;  //执行脚本<br>            root.Properties["AccessRead"][0] = true;<br>            root.Properties["DefaultDoc"][0] = "default.aspx";<br>            root.Invoke("AppCreate", true);<br>            root.CommitChanges();<br>            dEntry.CommitChanges();

《3》为新站点创建应用程序

foreach(DirectoryEntry item in root.Children)   //检查是否存在AppDir的应用程序
{
    if (item.SchemaClassName == "IIsWebVirtualDir" && item.Name=="AppDir")
    {
        root.Children.Remove(item);//删除
        break;
    }
}
DirectoryEntry appDir = root.Children.Add("AppDir", "IIsWebVirtualDir");  //注意第二个参数IIsWebVirtualDir.
appDir.Invoke("AppCreate", true);
appDir.Properties["Path"][0] = @"C:\Users\Administrator\Desktop\MyFolder";
appDir.Properties["AccessScript"][0] = true;
appDir.Properties["AccessRead"][0] = true;
appDir.CommitChanges();

 2.使用Microsoft.Web.Administration空间中的类,使用更加简洁而且易于理解。【注意:在使用Microsoft.Web.Administration时,应将Project的属性页面application选项卡中的TargetFramework更改为.net framework 4】。Microsoft.Web.Administration.dll在如下地址:%systemroot%\WINDOWS\system32\inetsrv.先看下面我使用的代码在默认站点下创建application。

复制代码
        private void ManageIIS()
        {
           try
           {
            ServerManager sm = new ServerManager();  
            ApplicationPool newPool = sm.ApplicationPools["NewPool"];
            Configuration config = sm.GetApplicationHostConfiguration();
            if (newPool != null)
            {
                 sm.ApplicationPools.Remove(newPool);
            }
            newPool = sm.ApplicationPools.Add("NewPool");
            newPool.ManagedRuntimeVersion = "v4.0";
            newPool.ManagedPipelineMode = ManagedPipelineMode.Classic;
           
            //create application
            Site defaultSite = sm.Sites["Default Web Site"];
            Application newApplication = defaultSite.Applications["/NewApplication"];
            if (newApplication != null)
            {
                defaultSite.Applications.Remove(newApplication);  //delete this application
                config.RemoveLocationPath("Default Web Site/NewApplication"); //delete the node of the applicationHostConfig.config file with this application
            }
            newApplication = defaultSite.Applications.Add("/NewApplication",@"E:\PrismModule.Web");
            newApplication.ApplicationPoolName = "NewPool";
       
            //set the application attribute in the applicationHostConfig.config file.
            config = sm.GetApplicationHostConfiguration();
            string path = "system.webServer/directoryBrowse";//the attribue path in the applictionHostConfig.config file.
            ConfigurationSection dbS = config.GetSection(path, "Default Web Site/NewApplication");
            dbS.Attributes["enabled"].Value = true;
            dbS = config.GetSection("system.webServer/security/access", "Default Web Site/NewApplication");
               
            sm.CommitChanges();
          }
          catch (Exception e)
          {
             throw e;
           }    
        }
复制代码

  代码比较简单,在写这段代码的时候碰到的主要问题是如何设置自己新建的application的属性。IIS7与其他版本的IIS区别是它将所有的配置信息(可读写,可执行script,匿名访问,目录浏览,默认页等)存储在各种.config文件,要想修改属性还需要了解各种config文件之间的关系。

  【引用MSDN:IIS 7.0 具有新的委派配置系统,它基于分布式 XML 配置文件的层次结构。此层次结构由全局 applicationHost.config 文件(该文件包含服务器级别的配置默认设置)以及应用程序的目录结构中的分布式 web.config 文件组成。这些文件与 ASP.NET 应用程序框架用于以可移植方式存储应用程序设置的 web.config 文件是相同的文件。因而可以使用干净和强大结构化的 XML 指令,并排地存储 IIS 和 ASP.NET 配置。

  下面看看applicationHost.config文件的结构:

  在<configSections>节点中定义了3个sectionGroup节点,在sectionGroup中包含section。section定义了属性的name,attribute等。当需要设置新建application的属性时,就要查看name="system.webServer"下面列出的一些属性,如下图:

  如图中所示,列出了一些对应属性名称。每个节点的overrideModeDefault=”Deny|Allow"将决定此属性是否被锁定。Deny表示锁定,即不能在application对应文件夹中的web.config中修改。Allow则允许将此配置信息写到applicaiton问价夹对应的web.config中。IIS7.0默认允许在web.config中被修改的配置信息有4个:DefaultDocument(默认文档),Directory browseing(目录浏览),Http protocol,Http redirect。其它的均不能在web.config中修改。如果想修改,必须IIS管理员将相应的section中的overrideModeDefault设为Allow。或者你就是管理员,直接在applicationHost.config中设置。applicationHost.config文件中默认设置了可读,执行script(handlers节点中)。

  下面主要解释一下config配置信息代码:

 Configuration config = sm.GetApplicationHostConfiguration();
 string path = "system.webServer/directoryBrowse";//the attribue path in the applictionHostConfig.config file.
 ConfigurationSection dbS = config.GetSection(path, "Default Web Site/NewApplication");
 dbS.Attributes["enabled"].Value = true;

  这段代码将新建的NewApplication的目录浏览属性设置为true,并接结果保存在applicationHost.config文件中。              ServerManager.GetApplicationHostConfiguration()方法将得到applicationHost.config对象。

  根据上图中的system.webServer节点的结构关系,可以得到需要修改的属性路径:path="system.webServer/directoryBrowse";

  方法config.GetSection(path,"Default Web Site/NewApplication”),第一参数指出修改的片段,第二个参数指出这个修改将应用到那个server。应为新建的application在默认站点下面所有参数为:Default Web Site/NewApplication。

      dbS.Attributes[”enabled"].Value=true;即设置为可以目录浏览。当调用ServerManager.CommitChanges()后,将保存。结构是applicationHost.config文件中将多出一个如下的片段。

  另一个常用的属性SSL的设置和上面的类似,当设置”要求ssl"选项时,applicationhost.config文件中将产生如下变化:

通过设置此属性,所有请求此application 内容的url请求都必须以”https"开头。

  应为Directory browsing默认是被允许在application文件夹的web.config文件修改的。因此,可以将此配置的修改保存在web.config文件中,这样可以轻松的用xcopy部署应用。方法基本相同,只是在获取Configuration类的使用应使用Application.GetWebConfiguration()获得一个实例对象。完整代码如下:

 Configuration cFile = newApplication.GetWebConfiguration();
 ConfigurationSection section = cFile.GetSection("system.webServer/directoryBrowse");
 dbS.Attributes["enabled"].Value = true;

  一个别忘了调用ServerManager.CommitChanges()方法保存修改,这些修改将保存到web.config文件中。它也是在文件中添加了一段xml片段,如下:

  

以上是自己学习时的过程,也可能有不对的地方。附上几篇参考的文章:

http://www.make-awesome.com/2010/12/automating-iis7-setup-with-microsoft-web-administration/

http://msdn.microsoft.com/zh-cn/magazine/cc163453.aspx

http://www.soft-bin.com/html/2010/07/28/use_csharp_to_control_iis.html