http://www.sufeinet.com/plugin.php?id=keke_group

苏飞论坛

 找回密码
 马上注册

QQ登录

只需一步,快速开始

分布式系统框架(V2.0) 轻松承载百亿数据,千万流量!讨论专区 - 源码下载 - 官方教程

HttpHelper爬虫框架(V2.7-含.netcore) HttpHelper官方出品,爬虫框架讨论区 - 源码下载 - 在线测试和代码生成

HttpHelper爬虫类(V2.0) 开源的爬虫类,支持多种模式和属性 源码 - 代码生成器 - 讨论区 - 教程- 例子

查看: 24551|回复: 9

[IIS] C#实现IIS创建配置站点和设置IIS Web服务扩展

[复制链接]
发表于 2012-11-22 13:38:36 | 显示全部楼层 |阅读模式
                                            C#实现IIS创建配置站点和设置IIS Web服务扩展

在网上看到一个文章是关于这块的,不过代码没有使用代码工具看着很不方便 ,转过来方便 大家阅读啊
1、新建站点
DirectoryEntry serviceEntry = new DirectoryEntry("IIS://localhost/W3SVC");
int SiteID = this.GetSiteID();//这里我们获取一个网站的名称,这里需要说明一下的是我们IIS默认安装完成后会有一个默认的站点,这个默 认站点的名称就是1,为了避免我们这里新建的站点我名字与IIS现有的站点名称相同,所以我用GetSiteID()自动得到一个名称,这个函数的实现下面会给出
DirecotryEntry newEntry = serviceEntry.Children.Add(SiteID.ToString(), "IIsWebServer");
newEntry.Properties["ServerComment"].Value = "MyWebSite";//这里是设置站点的别名
int nPort = this.GenerateSitePort(Port);//这里得到一个端口号,由于端口号会出现重复,所以我用GenerateSitePort函数进行处理,如果Port在当前IIS中没有使用,则返回Port,如果使用了,侧随机分配一个,这个函数下面也会给出
newEntry.Properties["ServerBindings"].Value = ServerIP + ":" + nPort + ":";//这一句设置站点的IP地址和端口号
newEntry.CommitChanges();//到些站点我们创建完成
2、创建虚拟目录和应用程序
DirectoryEntry vdEntry = null;//这里会判断当前站点下是否存在虚拟目录,因为我发现在Windows Server 2003和WindowsServer 2008上面是不一样的,有些是创建完站点它自动为你添加一个虚拟目录,有些则不会,所以这里为了实现通用性,我们判断一下,有的话就去Find查找到,没有就Add添加一个
[C#] 纯文本查看 复制代码
if (this.ExistVirtualDirectory(newEntry))
{
     vdEntry = newEntry.Children.Find("ROOT", "IIsWebVirtualDir");
}
else
{
     vdEntry = newEntry.Children.Add("ROOT", "IIsWebVirtualDir");
}
vdEntry.Properties["Path"].Value = WebSitePath;//这个WebSitePath是站点主目录的路径
vdEntry.CommitChanges();//虚拟目录创建完成
vdEntry.Invoke("AppCreate", true);//这里是创建应用程序
vdEntry.Properties["AppFriendlyName"].Value = "默认应用程序";//应用程序的名称
vdEntry.Properties["AccessRead"][0] = true;//读取访问的权限
vdEntry.Properties["AccessScript"][0] = true;//脚本访问权限 PS:可根据需要开放权限
vdEntry.CommitChanges();//应用程序添加完成
serviceEntry.CommitChanges();//整个站点创建和配置完成
//下面我把上面用到的几个函数的代码提供出来
//为新站点分配名称
private int GetSiteID()
{
     int Result = 1;
     DirectoryEntry serviceEntry = new DirectoryEntry("IIS://localhost/W3SVC");
     foreach (DirecotryEntry entry in serviceEntry.Children)
    {
        if (entry.SchemaClassName == "IIsWebServer")
        {
            int SiteID = 1;
            try
            {
                SiteID = int.Parse(entry.Name);
            }
            catch{continue;};
            if (SiteID == Result)
            {
                Result++;
            }
        }
    }
    return Result;
}
//获取端口号
private int GenerateSitePort(int Port)
{
     if (this.SitePortExist(Port))
     {
         Random rand = new Random();
         int newPort = rand.Next(1025, 65535);
         return GenerateSitePort(newPort);
     }
     else
     {
         return Port;
     }
}
//判断端口号是否存在,true存在,false不存在
private bool SitePortExist(int Port)
{
     DirectoryEntry serviceEntry = new DirectoryEntry("IIS://localhost/W3SVC");
     foreach (DirectoryEntry entry in serviceEntry.Children)
     {
         if (entry.SchemaClassName == "IIsWebServer")
         {
             if (entry.Properties["ServerBindings"].Value != null)
             {
                 string Binding = entry.Properties["ServerBindings"].Value.ToString().Trim();
                 //这个IP和端口的绑定IIS中是以冒号分隔的,如:127.0.0.1:8000:形式,所以这里我们要分隔一下,取第二个就是端口了
                 string[] Info = Binding.Split(':');
                 if (Port.ToString().Trim() == Info[1].Trim())
                 {
                      return true;
                 }
                 break;
              }
          }
     }
     return false;
}


3、设置Web服务扩展
这一点也是让我比较头痛的,查找了N久的MSDN才大概了解怎么做
在这里因为我的需要,我是需要使用2.0的框架支持,因为Windows Server 2003默认都为安装1.1的框架,所以为了避免这两个的冲突,我在这里判断IIS当前安装的版本
[C#] 纯文本查看 复制代码
private void RegisterIIS(string InstallPath)
{
    try
    {
        DirectoryEntry service = new DirectoryEntry("IIS://localhost/W3SVC");
        bool ExistLow = false;//是否存在1.1
        bool ExistHigh = false;//是否存在2.0
        if (service.Properties["WebSvcExtRestrictionList"] == null)
        {
            return;
        }
        //service.Properties["WebSvcExtRestrictionList"]会得到当前IIS的所有Web服务扩展选项,这们这里遍历查找安装了哪些版本的framework
        for (int i = 0; i < service.Properties["WebSvcExtRestrictionList"].Count; i++)
        {
            if (service.Properties["WebSvcExtRestrictionList"].ToString().Trim().IndexOf("ASP.NET v1.1.4322") > -1)
            {
                ExistLow = true;
                break;
            }
            if (service.Properties["WebSvcExtRestrictionList"].ToString().Trim().IndexOf("ASP.NET v2.0.50727") > -1)
            {
                ExistHigh = true;
                break;
            }
        }
        //----begin---因为避免两个版本的冲突,所以这里判断如果存在低版本或高版本的没有安装,这里都会运行一个批处理来卸载所有版本,安装2.0版本
        //这个“注册IIS.bat”其实就是下面两行      
        //                   %WINDIR%/Microsoft.NET/Framework/v2.0.50727/aspnet_regiis -ua
        //                   %WINDIR%/Microsoft.NET/Framework/v2.0.50727/aspnet_regiis -i

        if (ExistLow == true || ExistHigh == false)
        {
            Process process = new Process();
            process.StartInfo.FileName = InstallPath.TrimEnd('//') + "//注册IIS.bat";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
            process.WaitForExit();
            process.Close();
        }
        //--end----
        //这里就是关键了,因为即使安装了2.0版本,但ASP.NET v2.0.50727这一项可能是禁用状态,所以我要启用它
        //这里调用了EnableWebServiceExtension方法,从方法的名称我们可以看出这个函数就是启用Web服务扩展的方法
        //同时在这里我也介绍几个其它的方法
        //DisableWebServiceExtension----表示禁用某一个Web服务扩展,参数就是Web服务扩展的名称
        //RemoveApplication-----------------删除应用程序
        //.....等等,感兴趣的话,大家可以查一下MSDN,这个是提供了很多方法供大家使用
        service.Invoke("EnableWebServiceExtension", "ASP.NET v2.0.50727");
     }
     catch { }
}

那么这里我们对IIS创建站点,以及站点的设置和IIS的配置就完成了,但是程序中还有一些隐患,就是我们创建的站点的别名是不能相同的,在这里我也用一个函数进行了处理
[C#] 纯文本查看 复制代码
//清除相同别名的站点

private void ClearSameSite(string SiteAlias)
{
    DirectoryEntry rootEntry = new DirectoryEntry("IIS://localhost/W3SVC");
    foreach (DirectoryEntry entry in rootEntry.Children)
    {
        if (entry.SchemaClassName == "IIsWebServer")
        {
            if (entry.Properties["ServerComment"].Value != null && entry.Properties["ServerComment"].Value.ToString().Trim() == SiteAlias)
           {
                  rootEntry.Children.Remove(entry);
                  break;
           }
        }
    }
}

那么我用了一个函数对创建站点进行了整合
[C#] 纯文本查看 复制代码
private void CreateNewWebSite(string SiteAlias, string IPAddress, int Port, string DirPath)
{
     this.ClearSameSite(SiteAlias);
     DirectoryEntry serviceEntry = new DirectoryEntry("IIS://localhost/W3SVC");
     int SiteID = this.GetSiteID();
     DirecotryEntry newEntry = serviceEntry.Children.Add(SiteID.ToString(), "IIsWebServer");
     newEntry.Properties["ServerComment"].Value = SiteAlias;
     int nPort = this.GenerateSitePort(Port);
     newEntry.Properties["ServerBindings"].Value = IPAddress+ ":" + nPort + ":";
     newEntry.CommitChanges();
     DirectoryEntry vdEntry = null;
     if (this.ExistVirtualDirectory(newEntry))
     {
          vdEntry = newEntry.Children.Find("ROOT", "IIsWebVirtualDir");
     }
     else
     {
         vdEntry = newEntry.Children.Add("ROOT", "IIsWebVirtualDir");
     }
     vdEntry.Properties["Path"].Value = DirPath;
     vdEntry.CommitChanges();
     vdEntry.Invoke("AppCreate", true);
     vdEntry.Properties["AppFriendlyName"].Value = "默认应用程序";
     vdEntry.Properties["AccessRead"][0] = true;
     vdEntry.Properties["AccessScript"][0] = true;
     vdEntry.CommitChanges();
     serviceEntry.CommitChanges();
}


还有一个简单的办法启用"ASP.NET v2.0.50727",那就是把上面的脚本文件改为下面两行
[C#] 纯文本查看 复制代码
%WINDIR%/Microsoft.NET/Framework/v2.0.50727/aspnet_regiis -ua
%WINDIR%/Microsoft.NET/Framework/v2.0.50727/aspnet_regiis -i -enable

当然要是控制其它的项可能就得用上面的程序来实现了


1. 开通SVIP会员,免费下载本站所有源码,不限次数据,不限时间
2. 加官方QQ群,加官方微信群获取更多资源和帮助
3. 找站长苏飞做网站、商城、CRM、小程序、App、爬虫相关、项目外包等点这里
发表于 2013-1-5 19:57:27 | 显示全部楼层
ExistVirtualDirectory  这个是什么?
发表于 2013-1-6 08:52:22 | 显示全部楼层
我都是手动设置的  原来C# 也能操作 学习
 楼主| 发表于 2013-1-6 10:01:36 | 显示全部楼层
yisa 发表于 2013-1-5 19:57
ExistVirtualDirectory  这个是什么?

虚拟目录
发表于 2013-3-7 10:15:49 | 显示全部楼层
学习了
发表于 2013-5-4 11:47:54 | 显示全部楼层
感激涕零,谢谢楼主的好贴
发表于 2013-6-25 05:11:16 | 显示全部楼层
请问大家有什么看法?我绝对喜欢这个帖子
发表于 2013-7-31 09:41:44 | 显示全部楼层
这个资料不错~
发表于 2013-8-1 23:40:35 | 显示全部楼层
受教了,学习中……
发表于 2014-5-14 14:25:16 | 显示全部楼层
有点乱哦
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 马上注册

本版积分规则

QQ|手机版|小黑屋|手机版|联系我们|关于我们|广告合作|苏飞论坛 ( 豫ICP备18043678号-2)

GMT+8, 2024-6-16 13:32

© 2014-2021

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