VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • 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。

建立站点

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

修改站点

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

删除站点

?
1
2
3
Site site=sm.Sites["乐博网"];
sm.Sites.Remove(site);
sm.CommitChanges();

站点操作

方法一:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#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

方法二:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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";
  }

同样的方式,也可以对网站对属性进行修改。

IIS的站点属性(详细内容,请查阅IIS帮助)

Read only properties of W3SVC/1/Root:             // 只读属性

AppIsolated = 2             属性指出应用程序是在进程内、进程外还是在进程池中运行。值 0 表示应用程序在进程内运行,值 1 表示进程外,值 2 表示进程池。

AppPackageID =           为事务提供 COM+ 应用程序标识符 (ID)。此 ID 在由组件服务管理的所有事务中使用。

AppPackageName =      为事务提供 COM+ 应用程序名。

AppRoot = /LM/W3SVC/1/ROOT 包含到应用程序根目录的配置数据库路径。

Caption =              提供对象的一段简短文本描述(一行字符串)。

Description =         提供对象的一段较长文本描述。

InstallDate =          表示安装对象的时间。缺少值并不表示对象没有安装。


相关教程