.net C# 程序控制IIS 添加站点域名绑定
注意使用时要有服务器管理员权限 ,可在Web.config 添加
<system.web> <identity impersonate="true" userName="服务器用户名" password="密码" /> </system.web>
先添加两个引用:
System.EnterpriseServices及System.DirectoryServices
然后再在代码中引用:
1 using System.DirectoryServices; 2 using System.EnterpriseServices;
然后就是如何添加绑定了:
1 public static void AddHostHeader(int siteid, string ip, int port, string domain)//增加主机头(站点编号.ip.端口.域名) 2 { 3 DirectoryEntry site = new DirectoryEntry("IIS://localhost/W3SVC/" + siteid); 4 PropertyValueCollection serverBindings = site.Properties["ServerBindings"]; 5 string headerStr = string.Format("{0}:{1}:{2}", ip, port, domain); 6 log4net.LogManager.GetLogger("root").Info(serverBindings.PropertyName + serverBindings.Value.ToString()); 7 if (!serverBindings.Contains(headerStr)) 8 { 9 serverBindings.Add(headerStr); 10 } 11 site.CommitChanges(); 12 }
其中,siteid,自己到IIS中看,ip不指定的话填"*",端口一般是80,域名是怎么多少就入多少
注意:
1、添加后,会自动重启站点;
2、如果里面某个域名,重复添加,网站在重启的过程中会起不来,那就完蛋了,这个必须要配合自己的数据库;
3、必须在web.config添加权限配置:
————————————————
<system.web> <identity impersonate="true" userName="Administrator" password="password" /> </system.web>
4、如果在IIS7中出现: DirectoryEntry配置IIS7出现ADSI Error:未知错误(0x80005000)
“控制面板”->“程序和功能”->面板左侧“打开或关闭windows功能”->“Internet信息服务”->“Web管理工具”->“IIS 6管理兼容性”->“IIS 元数据库和IIS 6配置兼容性”。更理想的解决方式是用 WMI provider操作IIS 7 ,可参见此篇文章http://msdn.microsoft.com/en-us/library/aa347459.aspx
————————————————
版权声明:本文为CSDN博主「hejisan」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/hejisan/java/article/details/71156796
其他方案:
using System; using System.DirectoryServices; using System.EnterpriseServices; using System.Text.RegularExpressions; namespace WebCloud.Builder { public class IIS { /// <summary> /// 获取最小ID,越小越好 /// </summary> /// <returns></returns> public int SiteId() { DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC"); // Find unused ID value for new web site int siteID = 1; foreach (DirectoryEntry e in root.Children) { if (e.SchemaClassName == "IIsWebServer") { int ID = Convert.ToInt32(e.Name); if (ID >= siteID) { siteID = ID + 1; } } } return siteID; } #region 建IIS站点 /// <summary> /// IIS站点 /// </summary> /// <param name="port">站点端口</param> /// <param name="siteName">站点ID</param> /// <param name="siteExplain">域名</param> /// <param name="defaultDoc">默认文档</param> public int CreateSite(string port, string siteName, string siteExplain, string defaultDoc, string pathToRoot,string UserId) { int mark = 0; try { // createAppPool(siteExplain); DirectoryEntry de = new DirectoryEntry("IIS://localhost/" + "w3svc"); //从活动目录中获取IIS对象。 object[] prams = new object[2] { "IIsWebServer", Convert.ToInt32(siteName) }; DirectoryEntry site = (DirectoryEntry)de.Invoke("Create", prams); //创建IISWebServer对象。 site.Properties["KeyType"][0] = "IIsWebServer"; site.Properties["ServerComment"][0] = siteExplain; //站点说明 site.Properties["ServerState"][0] = 2; //站点初始状态,1.停止,2.启动,3 site.Properties["ServerSize"][0] = 1; site.Properties["ServerBindings"].Add(":" + port + ":" + siteExplain); //站点端口 site.CommitChanges(); //保存改变 de.CommitChanges(); DirectoryEntry root = site.Children.Add("Root", "IIsWebVirtualDir"); //添加虚拟目录对象 root.Invoke("AppCreate", true); //创建IIS应用程序 root.Invoke("AppCreate3", new object[] { 2, UserId, true }); //创建应用程序池,并指定应用程序池为"HostPool","true"表示如果HostPool不存在,则自动创建 root.Properties["path"][0] = pathToRoot; //虚拟目录指向的物理目录 root.Properties["EnableDirBrowsing"][0] = true;//目录浏览 root.Properties["AuthAnonymous"][0] = true; root.Properties["AccessExecute"][0] = true; //可执行权限 root.Properties["AccessRead"][0] = true; root.Properties["AccessWrite"][0] = true; root.Properties["AccessScript"][0] = true;//纯脚本 root.Properties["AccessSource"][0] = false; root.Properties["FrontPageWeb"][0] = false; root.Properties["KeyType"][0] = "IIsWebVirtualDir"; root.Properties["AppFriendlyName"][0] = siteExplain; //应用程序名 root.Properties["AppIsolated"][0] = 2; root.Properties["DefaultDoc"][0] = defaultDoc; //默认文档 root.Properties["EnableDefaultDoc"][0] = true; //是否启用默认文档 root.CommitChanges(); site.CommitChanges(); root.Close(); site.Close(); de.CommitChanges(); //保存 site.Invoke("Start", null); //除了在创建过程中置初始状态外,也可在此调用方法改变状态 mark = 1; } catch { mark = 0; } return mark; } #endregion #region 域名绑定方法 public int AddHostHeader(int siteid, string ip, int port, string domain)//增加主机头(站点编号.ip.端口.域名) { int mark = 0; try { DirectoryEntry site = new DirectoryEntry("IIS://localhost/W3SVC/" + siteid); PropertyValueCollection serverBindings = site.Properties["ServerBindings"]; string headerStr = string.Format("{0}:{1}:{2}", ip, port, domain); if (!serverBindings.Contains(headerStr)) { serverBindings.Add(headerStr); } site.CommitChanges(); mark = 1; } catch { mark = 0; } return mark; } #endregion #region 删除主机头 public void DeleteHostHeader(int siteid, string ip, int port, string domain)//删除主机头(站点编号.ip.端口.域名) { DirectoryEntry site = new DirectoryEntry("IIS://localhost/W3SVC/" + siteid); PropertyValueCollection serverBindings = site.Properties["ServerBindings"]; string headerStr = string.Format("{0}:{1}:{2}", ip, port, domain); if (serverBindings.Contains(headerStr)) { serverBindings.Remove(headerStr); } site.CommitChanges(); } #endregion #region 删除站点 public void DelSite(string siteName) { string siteNum = GetWebSiteNum(siteName); string siteEntPath = String.Format("IIS://{0}/w3svc/{1}", "localhost", siteNum); DirectoryEntry siteEntry = new DirectoryEntry(siteEntPath); string rootPath = String.Format("IIS://{0}/w3svc", "localhost"); DirectoryEntry rootEntry = new DirectoryEntry(rootPath); rootEntry.Children.Remove(siteEntry); rootEntry.CommitChanges(); } public string GetWebSiteNum(string siteName) { Regex regex = new Regex(siteName); string tmpStr; string entPath = String.Format("IIS://{0}/w3svc", "localhost"); DirectoryEntry ent = new DirectoryEntry(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; } } } } return "没有找到要删除的站点"; } #endregion #region 创建应用程序池 static void createAppPool(string AppPoolName) { DirectoryEntry newpool; DirectoryEntry apppools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools"); newpool = apppools.Children.Add(AppPoolName, "IIsApplicationPool"); newpool.CommitChanges(); } #endregion #region 删除应用程序池 public void deleteAppPool(string AppPoolName) { bool ExistAppPoolFlag=false; try { DirectoryEntry apppools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools"); foreach (DirectoryEntry a in apppools.Children) { if (a.Name == AppPoolName) { ExistAppPoolFlag = true; a.DeleteTree(); // MessageBox.Show("应用程序池名称删除成功", "删除成功"); } } if (ExistAppPoolFlag == false) { // MessageBox.Show("应用程序池未找到", "删除失败"); } } catch { //MessageBox.Show(ex.Message, "错误"); } } #endregion } } ———————————————— 版权声明:本文为CSDN博主「seekboya」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/seekboya/java/article/details/7569703
C# 操作IIS加强版(添加,删除,启动,暂停网站,默认页,绑定信息) 转载自:https://www.cnblogs.com/qyq0323/p/11796574.html
主要功能如下
在本机的IIS创建Web网站
删除网站包括应用程序池
删除应用程序池
添加默认文档
删除默认文档
添加虚拟目录
删除虚拟目录
启动网站
暂停网站
根据网站名获取网站信息
获取所有网站的的网站数据
添加绑定信息(IP,端口,域名)
删除绑定信息
using Microsoft.Web.Administration; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AutoIIS.Helper { /// <summary> /// IIS操作类 /// </summary> public class IISHelper { #region 创建网站 /// <summary> /// 在本机的IIS创建Web网站 /// </summary> /// <param name="siteName">网站名</param> /// <param name="bindingInfo">host <example>"*:80:myhost.com"</example></param> /// <param name="physicalPath">网站路径</param> /// <returns>成功返回True,失败返回false</returns> public static bool CreateSite(string siteName, string bindingInfo, string physicalPath) { return CreateSite(siteName, "http", bindingInfo, physicalPath, true, siteName, ProcessModelIdentityType.ApplicationPoolIdentity, null, null, ManagedPipelineMode.Integrated, null); } /// <summary> /// 在本机的IIS创建Web网站 /// </summary> /// <param name="siteName">网站名</param> /// <param name="protocol">http头</param> /// <param name="bindingInformation">网站例如<example>"*:80:[url=http://www.sufeinet.com]www.sufeinet.com[/url]"</example></param> /// <param name="physicalPath">网站的路径</param> /// <param name="createAppPool">是否创建应用程序程序池</param> /// <param name="appPoolName">应用程序名</param> /// <param name="identityType">标识</param> /// <param name="appPoolUserName">用户名没有时用户名为Null即可</param> /// <param name="appPoolPassword">密码</param> /// <param name="appPoolPipelineMode">模式,经典还是集成</param> /// <param name="managedRuntimeVersion">.net版本</param> /// <returns>成功返回True,失败返回false</returns> public static bool CreateSite(string siteName, string protocol, string bindingInformation, string physicalPath, bool createAppPool, string appPoolName, ProcessModelIdentityType identityType, string appPoolUserName, string appPoolPassword, ManagedPipelineMode appPoolPipelineMode, string managedRuntimeVersion) { using (ServerManager mgr = new ServerManager()) { //删除网站和应用程序池 DeleteSite(siteName); Site site = mgr.Sites.Add(siteName, protocol, bindingInformation.ToLower(), physicalPath); // PROVISION APPPOOL IF NEEDED if (createAppPool) { ApplicationPool pool = mgr.ApplicationPools.Add(appPoolName); if (pool.ProcessModel.IdentityType != identityType) { pool.ProcessModel.IdentityType = identityType; } if (!String.IsNullOrEmpty(appPoolUserName)) { pool.ProcessModel.UserName = appPoolUserName; pool.ProcessModel.Password = appPoolPassword; } if (appPoolPipelineMode != pool.ManagedPipelineMode) { pool.ManagedPipelineMode = appPoolPipelineMode; } site.Applications["/"].ApplicationPoolName = pool.Name; } if (site != null) { mgr.CommitChanges(); return true; } } return false; } #endregion #region 删除网站和应用程序池 /// <summary> /// 删除网站包括应用程序池 /// </summary> /// <param name="siteName">网站名</param> /// <param name="isAppPool">是否删除应用程序池默认为删除</param> /// <returns>成功返回True,失败返回false</returns> public static bool DeleteSite(string siteName, Boolean isAppPool = true) { using (ServerManager mgr = new ServerManager()) { //判断web应用程序是否存在 if (mgr.Sites[siteName] != null) { if (isAppPool) { //判断应用程序池是否存在 if (mgr.ApplicationPools[siteName] != null) { mgr.ApplicationPools.Remove(mgr.ApplicationPools[siteName]); } } mgr.Sites.Remove(mgr.Sites[siteName]); mgr.CommitChanges(); return true; } else { return false; } } } /// <summary> /// 删除应用程序池 /// </summary> /// <param name="appPoolName">应用程序池名</param> /// <returns>成功返回True,失败返回false</returns> public static bool DeletePool(string appPoolName) { using (ServerManager mgr = new ServerManager()) { ApplicationPool pool = mgr.ApplicationPools[appPoolName]; if (pool != null) { mgr.ApplicationPools.Remove(pool); mgr.CommitChanges(); return true; } else { return false; } } } #endregion #region 默认文档 添加和删除 /// <summary> /// 添加默认文档 /// </summary> /// <param name="siteName">网站</param> /// <param name="defaultDocName">默认文档名</param> /// <returns>成功返回True,失败返回false</returns> public static bool AddDefaultDocument(string siteName, string defaultDocName) { using (ServerManager mgr = new ServerManager()) { Configuration cfg = mgr.GetWebConfiguration(siteName); ConfigurationSection defaultDocumentSection = cfg.GetSection("system.webServer/defaultDocument"); ConfigurationElement filesElement = defaultDocumentSection.GetChildElement("files"); ConfigurationElementCollection filesCollection = filesElement.GetCollection(); foreach (ConfigurationElement elt in filesCollection) { if (elt.Attributes["value"].Value.ToString() == defaultDocName) { return false;//添加时存在 } } try { //创建一个新的默认页 ConfigurationElement docElement = filesCollection.CreateElement(); docElement.SetAttributeValue("value", defaultDocName); filesCollection.Add(docElement); } catch (Exception) { return false;//添加时发生错误 } mgr.CommitChanges(); } return true;//添加成功 } /// <summary> /// 删除默认文档 /// </summary> /// <param name="siteName">网站</param> /// <param name="defaultDocName">默认文档名</param> /// <returns>成功返回True,失败返回false</returns> public static bool DeleteDefaultDocument(string siteName, string defaultDocName) { using (ServerManager mgr = new ServerManager()) { Configuration cfg = mgr.GetWebConfiguration(siteName); ConfigurationSection defaultDocumentSection = cfg.GetSection("system.webServer/defaultDocument"); ConfigurationElement filesElement = defaultDocumentSection.GetChildElement("files"); ConfigurationElementCollection filesCollection = filesElement.GetCollection(); //创建一个新的默认页 ConfigurationElement docElement = filesCollection.CreateElement(); bool isdefault = false; //不存在则返回 foreach (ConfigurationElement elt in filesCollection) { if (elt.Attributes["value"].Value.ToString() == defaultDocName) { docElement = elt; isdefault = true; } } if (!isdefault) { return false;//不存在 } try { filesCollection.Remove(docElement); } catch (Exception) { return false;//删除时发生错误 } mgr.CommitChanges(); } return true;//删除成功 } #endregion #region 虚拟目录添加和删除 /// <summary> /// 添加虚拟目录 /// </summary> /// <param name="siteName">网站名</param> /// <param name="vDirName">目录名</param> /// <param name="physicalPath">对应的文件夹路径</param> /// <returns>成功返回True,失败返回false</returns> public static bool CreateVDir(string siteName, string vDirName, string physicalPath) { using (ServerManager mgr = new ServerManager()) { Site site = mgr.Sites[siteName]; if (site == null) { return false; } site.Applications.Add("/" + vDirName, physicalPath); mgr.CommitChanges(); } return true; } /// <summary> /// 删除虚拟目录 /// </summary> /// <param name="siteName">网站名</param> /// <param name="vDirName">目录名</param> /// <returns>成功返回True,失败返回false</returns> public static bool DeleteVDir(string siteName, string vDirName) { using (ServerManager mgr = new ServerManager()) { Site site = mgr.Sites[siteName]; if (site == null) { return false; } site.Applications.Remove(site.Applications["/" + vDirName]); mgr.CommitChanges(); } return true; } #endregion #region 网站重启,暂停,启动 /// <summary> /// 启动网站 /// </summary> /// <param name="siteName">网站名</param> /// <returns>成功返回True,失败返回false</returns> public static bool Start(string siteName) { try { using (ServerManager mgr = new ServerManager()) { if (mgr.Sites[siteName].State == ObjectState.Stopped) { mgr.Sites[siteName].Start(); } mgr.CommitChanges(); } } catch (Exception) { return false; } return true; } /// <summary> /// 暂停网站 /// </summary> /// <param name="siteName">网站名</param> /// <returns>成功返回True,失败返回false</returns> public static bool Stop(string siteName) { try { using (ServerManager mgr = new ServerManager()) { if (mgr.Sites[siteName].State == ObjectState.Started) { mgr.Sites[siteName].Stop(); } mgr.CommitChanges(); } } catch (Exception) { return false; } return true; } #endregion #region 获取网站的信息 /// <summary> /// 根据网站名获取网站信息 /// </summary> /// <param name="siteName"></param> /// <returns></returns> public static Site GetSiteInfo(string siteName) { using (ServerManager mgr = new ServerManager()) { return mgr.Sites[siteName]; } } /// <summary> /// 获取所有的网站数据 /// </summary> /// <returns>SiteCollection</returns> public static SiteCollection GetSiteList() { using (ServerManager mgr = new ServerManager()) { return mgr.Sites; } } #endregion #region 添加绑定信息 /// <summary> /// 添加绑定信息 /// </summary> /// <param name="siteName">网站名</param> /// <param name="ip">ip</param> /// <param name="port">port</param> /// <param name="domain">domain</param> /// <param name="bindingProtocol">协议头如 http/https默认为http</param> /// <returns>成功返回True,失败返回false</returns> public static bool AddHostBinding(string siteName, string ip, string port, string domain, string bindingProtocol = "http") { try { using (ServerManager mgr = new ServerManager()) { string binginfo = string.Format("{0}:{1}:{2}", ip, port, domain).ToLower(); BindingCollection binding = mgr.Sites[siteName].Bindings; binding.Add(binginfo, bindingProtocol); mgr.CommitChanges(); } } catch (Exception) { return false; } return true; } /// <summary> /// 删除绑定信息 /// </summary> /// <param name="siteName">网站名</param> /// <param name="ip">ip</param> /// <param name="port">port</param> /// <param name="domain">domain</param> /// <returns>成功返回True,失败返回false</returns> public static bool DeleteHostBinding(string siteName, string ip, string port, string domain) { try { using (ServerManager mgr = new ServerManager()) { string binginfo = string.Format("{0}:{1}:{2}", ip, port, domain).ToLower(); foreach (Binding item in mgr.Sites[siteName].Bindings) { if (item.BindingInformation == binginfo) { mgr.Sites[siteName].Bindings.Remove(item); break; } } mgr.CommitChanges(); } } catch (Exception) { return false; } return true; } #endregion } }
调取代码
using AutoIIS.Helper; using Microsoft.Web.Administration; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace AutoIIS { public partial class Index : Form { public Index() { InitializeComponent(); } private void Index_Load(object sender, EventArgs e) { } //添加默认页 private void button1_Click(object sender, EventArgs e) { richTextBox1.Text += IISHelper.AddDefaultDocument("苏飞论坛", txtdefault.Text.Trim()); } //创建网站 private void button2_Click(object sender, EventArgs e) { richTextBox1.Text += IISHelper.CreateSite(txtsite.Text.Trim(), txtdomain.Text.Trim(), txtfile.Text.Trim()); } //删除默认文档 private void button3_Click(object sender, EventArgs e) { richTextBox1.Text += IISHelper.DeleteDefaultDocument("苏飞论坛", txtdefault.Text.Trim()); } //删除网站 private void button4_Click(object sender, EventArgs e) { richTextBox1.Text += IISHelper.DeleteSite(txtsite.Text.Trim()); } //删除 private void button6_Click(object sender, EventArgs e) { richTextBox1.Text += IISHelper.DeleteVDir(txtsite.Text.Trim(), txtxuniname.Text.Trim()); } //添加 private void button5_Click(object sender, EventArgs e) { richTextBox1.Text += IISHelper.CreateVDir(txtsite.Text.Trim(), txtxuniname.Text.Trim(), txtxunipath.Text.Trim()); } //启动 private void button7_Click(object sender, EventArgs e) { richTextBox1.Text += IISHelper.Start(txtsite.Text.Trim()); } //暂停 private void button8_Click(object sender, EventArgs e) { richTextBox1.Text += IISHelper.Stop(txtsite.Text.Trim()); } private void button9_Click(object sender, EventArgs e) { Site site = IISHelper.GetSiteInfo(txtsite.Text.Trim()); richTextBox1.Text += "网站名:" + site.Name + "\r\n"; richTextBox1.Text += "网站状态:" + site.State.ToString() + "\r\n"; foreach (var item in site.Bindings) { richTextBox1.Text += "host:" + item.Host + "\r\n"; richTextBox1.Text += "bind:" + item.BindingInformation.ToString() + "\r\n"; } richTextBox1.Text += "网站状态:" + site.Applications.ToString().ToString() + "\r\n"; } //添加 private void button10_Click(object sender, EventArgs e) { string[] strlist = txtdomain.Text.Trim().Split(':'); richTextBox1.Text += IISHelper.AddHostBinding(txtsite.Text.Trim(), strlist[0], strlist[1], strlist[2]); } //删除 private void button11_Click(object sender, EventArgs e) { string[] strlist = txtdomain.Text.Trim().Split(':'); richTextBox1.Text += IISHelper.DeleteHostBinding(txtsite.Text.Trim(), strlist[0], strlist[1], strlist[2]); } } }