C#如何控制IIS动态添加删除网站详解

目的是在Winform程序里面,可以直接启动一个HTTP服务端,给下游客户连接使用。

查找相关技术,有两种方法:

1.使用C#动态添加网站应用到IIS中,借用IIS的站群软件管理能力来提供HTTP接口。本文即对此做说明

2.在Winform程序中实现Web服务器逻辑,自己监听和管理客户端请求;

利用IIS7自带类库管理IIS现在变的更强大更方便,而完全可以不需要用DirecotryEntry这个类了(乐博网中很多.net管理iis6.0的文章都用到了DirecotryEntry这个类 ),Microsoft.Web.Administration.dll位于IIS的目录(%WinDir%\\System32\\InetSrv)下,使用时需要引用,它基本上可以管理IIS7的各项配置。

这里只举几个例子说明一下基本功能,更多功能请参考MSDN。

建立站点

string SiteName="乐博网"; //站点名称
string BindArgs="*:80:"; //绑定参数,注意格式
string apl="http"; //类型
string path="e:\\乐博网"; //网站路径
ServerManager sm = new ServerManager();
sm.Sites.Add(SiteName,apl,BindArgs,path);
sm.CommitChanges();

修改站点

Site site=sm.Sites["newsite"];
site.Name=SiteName;
site.Bindings[0].EndPoint.Port=9999;
site.Applications[0].VirtualDirectories[0].PhysicalPath=path;
sm.CommitChanges();

删除站点

Site site=sm.Sites["乐博网"];

sm.Sites.Remove(site);

sm.CommitChanges();

站点操作

#region CreateWebsite 添加网站

  public string CreateWebSite(string serverID, string serverComment, string defaultVrootPath, string HostName, string IP, string Port)
  {
   try
   {
    ManagementObject oW3SVC = new ManagementObject (_scope, new ManagementPath(@"IIsWebService='W3SVC'"), null);
    if (IsWebSiteExists (serverID))
    {
     return "Site Already Exists...";
    }

    ManagementBaseObject inputParameters = oW3SVC.GetMethodParameters ("CreateNewSite");
    ManagementBaseObject[] serverBinding = new ManagementBaseObject[1];

    serverBinding[0] = CreateServerBinding(HostName, IP, Port);

    inputParameters["ServerComment"] = serverComment;
    inputParameters["ServerBindings"] = serverBinding;
    inputParameters["PathOfRootVirtualDir"] = defaultVrootPath;
    inputParameters["ServerId"] = serverID;

    ManagementBaseObject outParameter = null;
    outParameter = oW3SVC.InvokeMethod("CreateNewSite", inputParameters, null);

    // 启动网站
    string serverName = "W3SVC/" + serverID;
    ManagementObject webSite = new ManagementObject(_scope, new ManagementPath(@"IIsWebServer='" + serverName + "'"), null);
    webSite.InvokeMethod("Start", null);

    return (string)outParameter.Properties["ReturnValue"].Value;

   }
   catch (Exception ex)
   {
    return ex.Message;
   }

  }

  public ManagementObject CreateServerBinding(string HostName, string IP, string Port)
  {
   try
   {
    ManagementClass classBinding = new ManagementClass(_scope, new ManagementPath("ServerBinding"), null);

    ManagementObject serverBinding = classBinding.CreateInstance();

    serverBinding.Properties["Hostname"].Value = HostName;
    serverBinding.Properties["IP"].Value = IP;
    serverBinding.Properties["Port"].Value = Port;
    serverBinding.Put();

    return serverBinding;
   }
   catch
   {
    return null;
   }
  }
  
  #endregion

  #region 添加网站事件

  protected void AddWebsite_Click(object sender, EventArgs e)
  {
   IISManager iis = new IISManager();

   iis.Connect();

   string serverID = "5556";
   string serverComment = "Create Website";
   string defaultVrootPath = @"D:\web";
   string HostName = "World";
   string IP = "";
   string Port = "9898";

   ReturnMessage.Text = iis.CreateWebSite(serverID,serverComment,defaultVrootPath,HostName,IP,Port);
  }

  #endregion

  #region DeleteSite 删除站点

  public string DeleteSite(string serverID)
  {
   try
   {
    string serverName = "W3SVC/" + serverID;
    ManagementObject webSite = new ManagementObject(_scope, new ManagementPath(@"IIsWebServer='" + serverName + "'"), null);
    webSite.InvokeMethod("Stop", null);
    webSite.Delete();
    webSite = null;

    return "Delete the site succesfully!";
   }
   catch (Exception deleteEx)
   {
    return deleteEx.Message;
   }
  }

  #endregion

方法二:

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
namespace WindowsApplication1
{
 class IISManager
 {
  public IISManager()
  {
  }
  public static string VirDirSchemaName = "IIsWebVirtualDir";
  private string _serverName;
  public string ServerName
  {
   get
   {
    return _serverName;
   }
   set
   {
    _serverName = value;
   }
  }

  /// <summary>  
  /// 创建網站或虚拟目录 
  /// </summary>  
  /// <param name="WebSite">服务器站点名称(localhost)</param>  
  /// <param name="VDirName">虚拟目录名称</param>  
  /// <param name="Path">實際路徑</param>  
  /// <param name="RootDir">true=網站;false=虛擬目錄</param> 
  /// <param name="iAuth">设置目录的安全性,0不允许匿名访问,1为允许,2基本身份验证,3允许匿名+基本身份验证,4整合Windows驗證,5允许匿名+整合Windows驗證...更多請查閱MSDN</param>  
  /// <param name="webSiteNum">1</param>  
  /// <param name="serverName">一般為localhost</param> 
  /// <returns></returns> 
  public bool CreateWebSite(string WebSite, string VDirName, string Path, bool RootDir, int iAuth, int webSiteNum, string serverName)
  {
   try
   {
    System.DirectoryServices.DirectoryEntry IISSchema;
    System.DirectoryServices.DirectoryEntry IISAdmin;
    System.DirectoryServices.DirectoryEntry VDir;
    bool IISUnderNT;

    // 
    // 确定IIS版本 
    //   
    IISSchema = new System.DirectoryServices.DirectoryEntry("IIS://" + serverName + "/Schema/AppIsolated");
    if (IISSchema.Properties["Syntax"].Value.ToString().ToUpper() == "BOOLEAN")
     IISUnderNT = true;
    else
     IISUnderNT = false;
    IISSchema.Dispose();
    //   
    // Get the admin object   
    // 获得管理权限  
    //   
    IISAdmin = new System.DirectoryServices.DirectoryEntry("IIS://" + serverName + "/W3SVC/" + webSiteNum + "/Root");
    //   
    // If we're not creating a root directory   
    // 如果我们不能创建一个根目录   
    //    
    if (!RootDir)
    {
     //    
     // If the virtual directory already exists then delete it    
     // 如果虚拟目录已经存在则删除  
     //
     foreach (System.DirectoryServices.DirectoryEntry v in IISAdmin.Children)
     {
      if (v.Name == VDirName)
      {
       // Delete the specified virtual directory if it already exists 
       try
       {
        IISAdmin.Invoke("Delete", new string[] { v.SchemaClassName, VDirName });
        IISAdmin.CommitChanges();
       }
       catch (Exception ex)
       {
        throw ex;
       }
      }
     }
    }
    //   
    // Create the virtual directory  
    // 创建一个虚拟目录  
    //   
    if (!RootDir)
    {
     VDir = IISAdmin.Children.Add(VDirName, "IIsWebVirtualDir");
    }
    else
    {
     VDir = IISAdmin;
    }
    //   
    // Make it a web application  
    // 创建一个web应用   
    //
    if (IISUnderNT)
    {
     VDir.Invoke("AppCreate", false);
    }
    else
    {
     VDir.Invoke("AppCreate", true);
    }
    //   
    // Setup the VDir  
    // 安装虚拟目录  
    //AppFriendlyName,propertyName,, bool chkRead,bool chkWrite, bool chkExecute, bool chkScript,, true, false, false, true 
    VDir.Properties["AppFriendlyName"][0] = VDirName; //应用程序名称 
    VDir.Properties["AccessRead"][0] = true; //设置读取权限 
    VDir.Properties["AccessExecute"][0] = false;
    VDir.Properties["AccessWrite"][0] = false;
    VDir.Properties["AccessScript"][0] = true; //执行权限[純腳本] 
    //VDir.Properties["AuthNTLM"][0] = chkAuth; 
    VDir.Properties["EnableDefaultDoc"][0] = true;
    VDir.Properties["EnableDirBrowsing"][0] = false;
    VDir.Properties["DefaultDoc"][0] = "Default.aspx,Index.aspx,Index.asp"; //设置默认文档,多值情况下中间用逗号分割 
    VDir.Properties["Path"][0] = Path;
    VDir.Properties["AuthFlags"][0] = iAuth;
    //  
    // NT doesn't support this property  
    // NT格式不支持这特性  
    //   
    if (!IISUnderNT)
    {
     VDir.Properties["AspEnableParentPaths"][0] = true;
    }
    // 
    // Set the changes  
    // 设置改变   
    //   
    VDir.CommitChanges();

    return true;
   }
   catch (Exception ex)
   {
    throw ex;
   }
  }
  /// <summary> 
  /// 獲取VDir支持的所有屬性 
  /// </summary> 
  /// <returns></returns> 
  public string GetVDirPropertyName()
  {
   //System.DirectoryServices.DirectoryEntry VDir; 
   const String constIISWebSiteRoot = "IIS://localhost/W3SVC/1/ROOT/iKaoo";
   DirectoryEntry root = new DirectoryEntry(constIISWebSiteRoot);
   string sOut = "";
   //下面的方法是得到所有属性名称的方法: 
   foreach (PropertyValueCollection pvc in root.Properties)
   {
    //Console.WriteLine(pvc.PropertyName); 
    sOut += pvc.PropertyName + ":" + pvc.Value.ToString() + "-----------";
   }
   return sOut;
  }
  /// <summary> 
  /// 創建虛擬目錄 
  /// </summary> 
  /// <param name="sDirName">虛擬目錄程式名稱</param> 
  /// <param name="sPath">實體路徑</param> 
  /// <param name="sDefaultDoc">黙認首頁,多個名稱用逗號分隔</param> 
  /// <param name="iAuthFlags">设置目录的安全性,0不允许匿名访问,1为允许,2基本身份验证,3允许匿名+基本身份验证,4整合Windows驗證,5允许匿名+整合Windows驗證...更多請查閱MSDN</param> 
  /// <param name="sWebSiteNumber">Win2K,2K3支持多個網站,本次操作哪個網站,黙認網站為1</param> 
  /// <returns></returns> 
  public bool CreateVDir(string sDirName, string sPath, string sDefaultDoc, int iAuthFlags, string sWebSiteNumber)
  {
   try
   {
    String sIISWebSiteRoot = "IIS://localhost/W3SVC/" + sWebSiteNumber + "/ROOT";
    DirectoryEntry root = new DirectoryEntry(sIISWebSiteRoot);
    foreach (System.DirectoryServices.DirectoryEntry v in root.Children)
    {
     if (v.Name == sDirName)
     {
      // Delete the specified virtual directory if it already exists 
      root.Invoke("Delete", new string[] { v.SchemaClassName, sDirName });
      root.CommitChanges();
     }
    }
    DirectoryEntry tbEntry = root.Children.Add(sDirName, root.SchemaClassName);

    tbEntry.Properties["Path"][0] = sPath;
    tbEntry.Invoke("AppCreate", true);
    //tbEntry.Properties["AccessRead"][0] = true; 
    //tbEntry.Properties["ContentIndexed"][0] = true; 
    tbEntry.Properties["DefaultDoc"][0] = sDefaultDoc;
    tbEntry.Properties["AppFriendlyName"][0] = sDirName;
    //tbEntry.Properties["AccessScript"][0] = true; 
    //tbEntry.Properties["DontLog"][0] = true; 
    //tbEntry.Properties["AuthFlags"][0] = 0; 
    tbEntry.Properties["AuthFlags"][0] = iAuthFlags;
    tbEntry.CommitChanges();
    return true;
   }
   catch (Exception ex)
   {
    throw ex;
   }
  }

 }

}
调用DEMO:
private void button1_Click(object sender, EventArgs e)
  {
   if (new IISManager().CreateWebSite("localhost", "Vtest", "E:\\DOC", false, 1, 1, "localhost"))
    lbInfo.Text = "Create Vtest OK"; 
  }
  private void button2_Click(object sender, EventArgs e)
  {
   txtPN.Text = new IISManager().GetVDirPropertyName();
  }
  private void button3_Click(object sender, EventArgs e)
  {
   if (new IISManager().CreateVDir("iKaoo", "E:\\DOC", "index.aspx,Default.aspx", 1, "1"))
    lbInfo.Text = "Create iKaoo OK";
  }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/3345.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【UE4 塔防游戏系列】07-子弹对敌人造成伤害

目录 效果 步骤 一、让子弹拥有不同伤害 二、敌人拥有不同血量 三、修改“BP_TowerBase”逻辑 四、发射的子弹对敌人造成伤害 效果 步骤 一、让子弹拥有不同伤害 为了让每一种子弹拥有不同的伤害值&#xff0c;打开“TotalBulletsCategory”&#xff08;所有子弹的父类…

【Spring Boot】Web开发 — Web开发简介

Web开发简介 首先介绍Spring Boot 提供的Web组件spring-boot-starter-web&#xff0c;然后介绍Controller和RestController注解&#xff0c;以及控制数据返回的ResponseBody注解&#xff0c;最后介绍Web配置&#xff0c;以便让读者对使用Spring Boot开发Web系统有初步的了解。…

linux下一个iic驱动(按键+点灯)-互斥

一、前提&#xff1a; 硬件部分&#xff1a; 1. rk3399开发板&#xff0c;其中的某一路iic&#xff0c;这个作为总线的主控制器 2. gd32单片机&#xff0c;其中的某一路iic&#xff0c;从设备。主要是按键上报和灯的亮灭控制。&#xff08;按键大约30个&#xff0c;灯在键的…

送呆萌的她一个皮卡丘(Python实现)

目录 1 呆萌的她 2 思维需要革新 3 送她的一个漂亮皮卡丘 4 Python完整代码奉上 1 呆萌的她 又是一季春风暖阳下, 你是一湾一湾羞涩的春波。 静静感受着&#xff0c; 你垂下的枝膊 在我的脸上轻轻抚摸 一对春燕,低低掠过 涟漪乍起&#xff0c;是你浅浅的笑窝...... 2 思…

(五)「消息队列」之 RabbitMQ 主题(使用 .NET 客户端)

0、引言 先决条件 本教程假设 RabbitMQ 已安装并且正在 本地主机 的标准端口&#xff08;5672&#xff09;上运行。如果您使用了不同的主机、端口或凭证&#xff0c;则要求调整连接设置。 获取帮助 如果您在阅读本教程时遇到问题&#xff0c;可以通过邮件列表或者 RabbitMQ 社区…

56 # 实现 pipe 方法进行拷贝

pipe 是异步的&#xff0c;可以实现读一点写一点&#xff0c;管道的优势&#xff1a;不会淹没可用内存&#xff0c;但是在导入的过程中无法获取到内容 const fs require("fs"); const path require("path");fs.createReadStream(path.resolve(__dirname…

前端 | (七)浮动 | 尚硅谷前端html+css零基础教程2023最新

学习来源&#xff1a;尚硅谷前端htmlcss零基础教程&#xff0c;2023最新前端开发html5css3视频 文章目录 &#x1f4da;浮动介绍&#x1f407;元素浮动后的特点&#x1f407;浮动小练习&#x1f525;盒子1右浮动&#x1f525;盒子1左浮动&#x1f525;所有盒子都浮动&#x1f5…

Python 闭包 装饰器

闭包定义&#xff1a;在函数嵌套的前提下&#xff0c;内部函数使用了外部函数的变量&#xff0c;并且外部函数返回了内部函数&#xff0c;我们把这个使用外部函数变量的内部函数称为闭包. 下面实现一个在执行方法的前后打印日志的场景 第一种方法装饰器 1.定义外层函数(要求…

vscode 添加 ros头文件

解决 vscode不能支持ROS相关头文件和没有智能提示问题 vscode 编写pakage源文件代码,#include<ros/ros.h>等头文件时报错,无法运行智能提示 1.vscode中CTRL+P 2.键入ext install ms-iot.vscode-ros 按回车,等待下载ros插件 3.修改c_cpp_properties.json文件 鼠标…

数学建模 插值算法

有问题 牛顿差值也有问题它们都有龙格现象&#xff0c;一般用分段插值。 插值预测要比灰色关联预测更加准确&#xff0c;灰色预测只有2次 拟合样本点要非常多&#xff0c;样本点少差值合适

Spring底层

配置文件 配置优先级 之前讲解过&#xff0c;可以用这三种方式进行配置 那如果这三种都进行了配置&#xff0c;那到底哪一份生效呢&#xff1f; 结论 优先级从大到小 properties>yml>yaml然后就是现在一般都用yml文件进行配置 其他配置方式 除了配置文件外 还有不同…

java Spring中使用到的设计模式

单例模式 单例模式(Singleton Pattern)是java中最简单的设计模式之一。这种类型的设计模式属于创建型模式&#xff0c;它提供了一种创建对象的最佳方式。这种模式涉及到一个单一的类&#xff0c;该类负责创建自己的对象&#xff0c;同时确保只有单个对象被创建。这个类提供了一…

电压放大器在超声波焊接中的作用以及应用

电压放大器是一种运用于电子设备中的信号放大器&#xff0c;主要作用是将小信号放大为更高幅度的信号。在超声波焊接中&#xff0c;电压放大器起到了重要的作用&#xff0c;它可以将从传感器采集到的微小信号放大为能够被检测和处理的合适大小的信号。 超声波焊接是现代工业生产…

微信怎么自动加好友,通过好友后自动打招呼

很多客户朋友每天花大量的时间用手机搜索添加好友&#xff0c;这样的添加很集中也容易频繁&#xff0c;而且效率还低。对方通过后&#xff0c;有时也不能及时和客户搭建链接&#xff0c;导致客户也流失了。 现在可以实现自动添加和自动打招呼哦&#xff0c;只需要导入数据、设置…

【从零开始学CSS | 第二篇】伪类选择器

目录 前言&#xff1a; 伪类选择器&#xff1a; 常见的伪类选择器&#xff1a; 举例&#xff1a; 小窍门&#xff1a; 总结: 前言&#xff1a; 上一篇文章我们详细的为大家介绍了一些常见的选择器&#xff0c;这几篇我们将再次介绍CSS中的一个常见选择器——伪类选择器&am…

设计模式之适配器模式

写在前面 适配器设计模式属于结构型设计模式的一种&#xff0c;本文一起来看下。 1&#xff1a;介绍 1.1&#xff1a;什么时候适配器设计模式 当现有接口客户端无法直接调用时&#xff0c;我们可以考虑适配器设计模式&#xff0c;来定义一个能够供客户端直接调用的接口&…

软件测试的分类

代码分类&#xff1a; 1、黑盒测试 2、白盒测试 3、灰黑测试 黑盒测试&#xff1a; 把测试的对象看成是一个黑色的盒子的&#xff0c;看不到里面内部的结构&#xff0c;是对软件的一种功能性的测试。 白盒测试&#xff1a; 就是把测试的对象看成是一个透明的盒子&#x…

测试老鸟总结,性能测试-最佳并发和最大并发,性能测试实施...

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 性能测试&#xf…

curl操作

下载路径&#xff1a;https://curl.se/windows/ 参考&#xff1a;https://blog.csdn.net/weixin_45191386/article/details/130652821 操作&#xff1a; curl http://localhost:8085/api/v1/aaa/bbbb/?ccc 652781344055627776

Maven下载依赖的顺序及配置文件说明

在 Maven 中&#xff0c;当下载依赖项时&#xff0c;存在多个仓库时会按照以下优先级顺序进行搜索&#xff1a; 本地仓库&#xff1a;Maven 会首先在本地的 Maven 仓库中查找依赖项。 私有仓库&#xff08;私服&#xff09;&#xff1a;如果在本地仓库中未找到依赖项&#xf…