c#操作IIS站点
/// <summary>
/// 获取本地IIS版本
/// </summary>
/// <returns></returns>
public string GetIIsVersion()
{
try
{
DirectoryEntry entry = new DirectoryEntry("IIS://localhost/W3SVC/INFO");
string version = entry.Properties["MajorIISVersionNumber"].Value.ToString();
return version;
}
catch (Exception se)
{
//说明一点:IIS5.0中没有(int)entry.Properties["MajorIISVersionNumber"].Value;属性,将抛出异常 证明版本为 5.0
return string.Empty;
}
}
/// <summary>
/// 创建虚拟目录网站
/// </summary>
/// <param name="webSiteName">网站名称</param>
/// <param name="physicalPath">物理路径</param>
/// <param name="domainPort">站点+端口,如192.168.1.23:90</param>
/// <param name="isCreateAppPool">是否创建新的应用程序池</param>
/// <returns></returns>
public int CreateWebSite(string webSiteName, string physicalPath, string domainPort, bool isCreateAppPool)
{
DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
// 为新WEB站点查找一个未使用的ID
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; }
}
}
// 创建WEB站点
DirectoryEntry site = (DirectoryEntry)root.Invoke("Create", "IIsWebServer", siteID);
site.Invoke("Put", "ServerComment", webSiteName);
site.Invoke("Put", "KeyType", "IIsWebServer");
site.Invoke("Put", "ServerBindings", domainPort + ":");
site.Invoke("Put", "ServerState", 2);
site.Invoke("Put", "FrontPageWeb", 1);
site.Invoke("Put", "DefaultDoc", "Default.html");
site.Invoke("Put", "ServerAutoStart", 1);
site.Invoke("Put", "ServerSize", 1);
site.Invoke("SetInfo");
// 创建应用程序虚拟目录
DirectoryEntry siteVDir = site.Children.Add("Root", "IISWebVirtualDir");
siteVDir.Properties["AppIsolated"][0] = 2;
siteVDir.Properties["Path"][0] = physicalPath;
siteVDir.Properties["AccessFlags"][0] = 513;
siteVDir.Properties["FrontPageWeb"][0] = 1;
siteVDir.Properties["AppRoot"][0] = "LM/W3SVC/" + siteID + "/Root";
siteVDir.Properties["AppFriendlyName"][0] = "Root";
if (isCreateAppPool)
{
DirectoryEntry apppools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
DirectoryEntry newpool = apppools.Children.Add(webSiteName, "IIsApplicationPool");
newpool.Properties["AppPoolIdentityType"][0] = "4"; //4
newpool.Properties["ManagedPipelineMode"][0] = "0"; //0:集成模式 1:经典模式
newpool.CommitChanges();
siteVDir.Properties["AppPoolId"][0] = webSiteName;
}
siteVDir.CommitChanges();
site.CommitChanges();
return siteID;
}
/// <summary>
/// 得到网站的物理路径
/// </summary>
/// <param name="rootEntry">网站节点</param>
/// <returns></returns>
public static string GetWebsitePhysicalPath(DirectoryEntry rootEntry)
{
string physicalPath = "";
foreach (DirectoryEntry childEntry in rootEntry.Children)
{
if ((childEntry.SchemaClassName == "IIsWebVirtualDir") && (childEntry.Name.ToLower() == "root"))
{
if (childEntry.Properties["Path"].Value != null)
{
physicalPath = childEntry.Properties["Path"].Value.ToString();
}
else
{
physicalPath = "";
}
}
}
return physicalPath;
}
/// <summary>
/// 获取站点列表
/// </summary>
public static List<IISInfo> GetServerBindings()
{
List<IISInfo> iisList = new List<IISInfo>();
string entPath = String.Format("IIS://localhost/w3svc");
DirectoryEntry ent = new DirectoryEntry(entPath);
foreach (DirectoryEntry child in ent.Children)
{
if (child.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))
{
if (child.Properties["ServerBindings"].Value != null)
{
object objectArr = child.Properties["ServerBindings"].Value;
string serverBindingStr = string.Empty;
if (IsArray(objectArr))//如果有多个绑定站点时
{
object[] objectToArr = (object[])objectArr;
serverBindingStr = objectToArr[0].ToString();
}
else//只有一个绑定站点
{
serverBindingStr = child.Properties["ServerBindings"].Value.ToString();
}
IISInfo iisInfo = new IISInfo();
iisInfo.siteNum = child.Name;//站点编号
iisInfo.SiteName = child.Properties["ServerComment"].Value.ToString();//站点名称
iisInfo.DomainPort = serverBindingStr;//绑定
iisInfo.AppPool = child.Children.Find("Root", "IISWebVirtualDir").Properties["AppPoolId"].Value.ToString();//应用程序池名称
DirectoryEntry siteEntry = new DirectoryEntry(String.Format("IIS://localhost/w3svc/{0}", child.Name));
iisInfo.SitePath = GetWebsitePhysicalPath(siteEntry);//获取站点路径
iisList.Add(iisInfo);
}
}
}
return iisList;
}
public static string GetServerBindingsString()//返回拼接字符串
{
string result = "";
string entPath = String.Format("IIS://localhost/w3svc");
DirectoryEntry ent = new DirectoryEntry(entPath);
foreach (DirectoryEntry child in ent.Children)
{
if (child.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))
{
if (child.Properties["ServerBindings"].Value != null)
{
object objectArr = child.Properties["ServerBindings"].Value;
string serverBindingStr = string.Empty;
if (IsArray(objectArr))//如果有多个绑定站点时
{
object[] objectToArr = (object[])objectArr;
serverBindingStr = objectToArr[0].ToString();
}
else//只有一个绑定站点
{
serverBindingStr = child.Properties["ServerBindings"].Value.ToString();
}
DirectoryEntry siteEntry = new DirectoryEntry(String.Format("IIS://localhost/w3svc/{0}", child.Name));
result += child.Name + "," + child.Properties["ServerComment"].Value.ToString() + "," + serverBindingStr + "," + child.Children.Find("Root", "IISWebVirtualDir").Properties["AppPoolId"].Value.ToString() + "," + GetWebsitePhysicalPath(siteEntry) + ";";
}
}
}
return result;
}
/// <summary>
/// 创建应用池
/// </summary>
/// <param name="appPoolName"></param>
/// <param name="Username"></param>
/// <param name="Password"></param>
/// <returns></returns>
public bool CreateAppPool(string appPoolName, string Username, string Password)
{
bool issucess = false;
try
{
//创建一个新程序池
DirectoryEntry newpool;
DirectoryEntry apppools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
newpool = apppools.Children.Add(appPoolName, "IIsApplicationPool");
//设置属性 访问用户名和密码 一般采取默认方式
newpool.Properties["WAMUserName"][0] = Username;
newpool.Properties["WAMUserPass"][0] = Password;
newpool.Properties["AppPoolIdentityType"][0] = "3";
newpool.CommitChanges();
issucess = true;
return issucess;
}
catch // (Exception ex)
{
return false;
}
}
public void CreateAppPool(string AppPoolName)
{
if (!IsAppPoolName(AppPoolName))
{
DirectoryEntry newpool;
DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
newpool = appPools.Children.Add(AppPoolName, "IIsApplicationPool");
newpool.CommitChanges();
MessageBox.Show(AppPoolName + "程序池增加成功");
}
////修改应用程序的配置(包含托管模式及其NET运行版本)
//ServerManager sm = new ServerManager();
//sm.ApplicationPools[AppPoolName].ManagedRuntimeVersion = "v4.0";
//sm.ApplicationPools[AppPoolName].ManagedPipelineMode = ManagedPipelineMode.Classic; //托管模式Integrated为集成 Classic为经典
//sm.CommitChanges();
//MessageBox.Show(AppPoolName + "程序池托管管道模式:" + sm.ApplicationPools[AppPoolName].ManagedPipelineMode.ToString() + "运行的NET版本为:" + sm.ApplicationPools[AppPoolName].ManagedRuntimeVersion);
}
/// <summary>
/// 判断程序池是否存在
/// </summary>
/// <param name="AppPoolName">程序池名称</param>
/// <returns>true存在 false不存在</returns>
private bool IsAppPoolName(string AppPoolName)
{
bool result = false;
DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
foreach (DirectoryEntry getdir in appPools.Children)
{
if (getdir.Name.Equals(AppPoolName))
{
result = true;
}
}
return result;
}
/// <summary>
/// 获取应用池列表
/// </summary>
/// <returns>应用池列表</returns>
public string AppPoolNameList()
{
string list = "";
DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
foreach (DirectoryEntry getdir in appPools.Children)
{
list += getdir.Name + ",";//应用池名称
}
if (list != "")
{
list = list.Substring(0, list.Length - 1);
}
return list;
}
/// <summary>
/// 根据站点名称查询对应应用池名称
/// </summary>
/// <param name="siteName"></param>
/// <returns></returns>
public string AppPoolNameBySiteName(string siteName)
{
string AppPoolName = "";
DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
foreach (DirectoryEntry website in root.Children)
{
if (website.SchemaClassName != "IIsWebServer") continue;
string comment = website.Properties["ServerComment"][0].ToString();
if (comment == siteName)
{
DirectoryEntry siteVDir = website.Children.Find("Root", "IISWebVirtualDir");
AppPoolName = siteVDir.Properties["AppPoolId"][0].ToString();
return AppPoolName;
}
}
return string.Empty;
}
/// <summary>
/// 建立程序池后关联相应应用程序及虚拟目录
/// </summary>
public void SetAppToPool(string appname, string poolName)
{
//获取目录
DirectoryEntry getdir = new DirectoryEntry("IIS://localhost/W3SVC");
foreach (DirectoryEntry getentity in getdir.Children)
{
if (getentity.SchemaClassName.Equals("IIsWebServer"))
{
//设置应用程序程序池 先获得应用程序 在设定应用程序程序池
//第一次测试根目录
foreach (DirectoryEntry getchild in getentity.Children)
{
if (getchild.SchemaClassName.Equals("IIsWebVirtualDir"))
{
//找到指定的虚拟目录.
foreach (DirectoryEntry getsite in getchild.Children)
{
if (getsite.Name.Equals(appname))
{
//【测试成功通过】
getsite.Properties["AppPoolId"].Value = poolName;
getsite.CommitChanges();
}
}
}
}
}
}
}
/// <summary>
/// 已知路径删除站点目录文件
/// </summary>
/// <param name="sitepath">网站路径</param>
public string DeleteSiteFile(string sitepath) //void DeleteSiteFile(string siteName)
{
try
{
Directory.Delete(sitepath, true);
return "删除站点成功";
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 根据站点名称删除站点目录文件
/// </summary>
/// <param name="siteName">网站路径</param>
public string DeleteSiteFileBySiteName(string siteName)
{
try
{
string siteNum = GetWebSiteNum(siteName);
DirectoryEntry siteEntry = new DirectoryEntry(String.Format("IIS://localhost/w3svc/{0}", siteNum));
string sitePath = GetWebsitePhysicalPath(siteEntry);//获取站点路径
DirectoryInfo dir = new DirectoryInfo(sitePath);
if (dir.Exists)
{
Directory.Delete(sitePath, true);
}
return "删除站点成功";
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 获取网站编号
/// </summary>
/// <param name="siteName"></param>
/// <returns></returns>
public string GetWebSiteNum(string siteName)
{
Regex regex = new Regex(siteName);
string tmpStr;
DirectoryEntry ent = new DirectoryEntry("IIS://localhost/w3svc");
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;
}
}
}
}
throw new Exception("没有找到我们想要的站点" + siteName);
}
/// <summary>
/// 获取网站编号
/// </summary>
private string getWebSiteNum(string siteName)
{
using (DirectoryEntry ent = new DirectoryEntry("IIS://localhost/w3svc"))
{
foreach (DirectoryEntry child in ent.Children)
{
if (child.SchemaClassName == "IIsWebServer")
{
if (child.Properties["ServerComment"].Value != null)
{
string tmpStr = child.Properties["ServerComment"].Value.ToString();
if (tmpStr.Equals(siteName))
{
return child.Name;
}
}
}
}
}
return string.Empty;
}
static Hashtable hs = new Hashtable();//创建哈希表,保存池中的站点
static string[] pls;//池数组
static string[] nums;//应用程序池中各自包含的网站数量
/// <summary>
/// 判断网站名与应用程序池名称是否相等
/// </summary>
/// <param name="wnames">网站名称</param>
/// <returns>相等为假</returns>
public bool chname(string wnames)
{
bool ctf = true;
pls = AppPoolNameList().Split(',');
foreach (string i in pls)
{
if (wnames == i)
ctf = false;
else ctf = true;
}
return ctf;
}
/// <summary>
/// 获得池数组对应的网站数量
/// </summary>
public void WebNums()
{
List<string> weblist = new List<string>();
pls = AppPoolNameList().Split(',');
foreach (string i in pls)
{
if (hs[i].ToString() != "")
weblist.Add(hs[i].ToString().Split(',').Length.ToString());
else
weblist.Add("0");
}
nums = weblist.ToArray();
}
/// <summary>
/// 移动网站到新池
/// </summary>
/// <param name="webns">网站名称</param>
/// <param name="poolold">旧池名称</param>
/// <param name="poolns">新池名称</param>
public void movepool(string webns, string poolold, string poolns)
{
pls = AppPoolNameList().Split(',');
try
{
DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
foreach (DirectoryEntry website in root.Children)
{
if (website.SchemaClassName != "IIsWebServer") continue;
string comment = website.Properties["ServerComment"][0].ToString();
if (comment == webns)
{
DirectoryEntry siteVDir = website.Children.Find("Root", "IISWebVirtualDir");
siteVDir.Invoke("Put", new object[2] { "AppPoolId", poolns });
siteVDir.CommitChanges();
website.Invoke("Put", new object[2] { "AppPoolId", poolns });
website.CommitChanges();
}
}
for (int i = 0; i < pls.Length; i++)//遍历旧池并修改原数目数组的数据
{
if (pls[i] == poolold)
{
nums[i] = (int.Parse(nums[i]) - 1).ToString();
string[] h = hs[poolold].ToString().Split(',');
string hnew = "";
foreach (string s in h)
if (s != webns)
{
if (hnew == "")
hnew = s;
else hnew += "," + s;
}
hs[poolold] = hnew;
if (hs[poolns].ToString() == "") hs[poolns] = webns;
else hs[poolns] += "," + webns;
}
if (pls[i] == poolns)
{
WebNums();
nums[i] = (int.Parse(nums[i]) + 1).ToString();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// 应用池操作
/// </summary>
/// <param name="AppPoolName">应用池名称</param>
/// Start开启 Recycle回收 Stop 停止
/// <returns></returns>
public string AppPoolOP(string AppPoolName, string state)
{
try
{
DirectoryEntry appPool = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
DirectoryEntry findPool = appPool.Children.Find(AppPoolName, "IIsApplicationPool");
findPool.Invoke(state, null);
appPool.CommitChanges();
appPool.Close();
return "操作成功";
}
catch (Exception ex)
{
return "操作失败";
}
}
/// <summary>
/// 判断object对象是否为数组
/// </summary>
public static bool IsArray(object o)
{
return o is Array;
}
c#操作IIS站点的更多相关文章
- C#操作IIS站点 Microsoft.Web.Administration.dll
利用IIS7自带类库管理IIS现在变的更强大更方便,而完全可以不需要用DirecotryEntry这个类了(网上很多.net管理iis6.0的文章都用到了DirecotryEntry这个类 ),Mic ...
- C#操作IIS程序池及站点的创建配置
最近在做一个WEB程序的安装包:对一些操作IIS进行一个简单的总结:主要包括对IIS进行站点的新建以及新建站点的NET版本的选择,还有针对IIS7程序池的托管模式以及版本的操作:首先要对Microso ...
- C#操作IIS程序池及站点的创建配置(转)
原文:http://www.cnblogs.com/wujy/archive/2013/02/28/2937667.html 最近在做一个WEB程序的安装包:对一些操作IIS进行一个简单的总结:主 ...
- C# 使用代码来操作 IIS
由于需要维护网站的时候,可以自动将所有的站点HTTP重定向到指定的静态页面上. 要操作 IIS 主要使用到的是“Microsoft.Web.Administration.dll”. 该类库不可以在引用 ...
- C#操作IIS完整解析
原文:C#操作IIS完整解析 最近在为公司实施做了一个工具,Silverlight部署早已是轻车熟路, 但对于非技术人员来说却很是头疼的一件事,当到现场实施碰到客户情况也各不相同, 急需一个类似系统备 ...
- 利用ASP.NET操作IIS (可以制作安装程序)
很多web安装程序都会在IIS里添加应用程序或者应用程序池,早期用ASP.NET操作IIS非常困难,不过,从7.0开始,微软提供了 Microsoft.Web.Administration 类,可以很 ...
- .net 程序 动态 控制IIS 站点域名绑定
第一步:引用 导入 System.EnterpriseServices及System.DirectoryServices 两个引用 程序引用: using System.DirectoryServic ...
- IIS站点报拒绝访问Temporary ASP.NET Files的解决办法
IIS站点本来运行的好好的,突然就出现了:Temporary ASP.NET Files拒绝访问的问题.遇到此类问题,请逐步排查,定可解决. 原因:Windows操作系统升级导致. 办法: 1.检查C ...
- IIS站点工作原理与ASP.NET工作原理
IIS站点工作原理与ASP.NET工作原理 一.IIS IIS 7.0工作原理图 两种模式: 1.用户模式(User Mode)(运行用户的程序代码.限制在特定的范围内活动.有些操作必须要受到Ker ...
随机推荐
- 用php模拟做服务端侦听端口
参考:http://www.cnblogs.com/thinksasa/archive/2013/02/26/2934206.html http://blog.csdn.net/alongken200 ...
- 使用mysql的长连接
有个资料看得我云里雾里的.现在用自己的言语来总结一下,写文字,能够加深自己的理解.也会在写的过程中帮助自己发现理解方面瑕疵,继续查资料求证. 短链接的缺点:创建一个连接,程序执行完毕后,就会自动断掉与 ...
- 关于javascript的一些知识以及循环
javascript的一些知识点:1.常用的五大浏览器:chrome,firefox,Safari,ie,opera 2.浏览器是如何工作的简化版:3.Js由ECMAjavascript;DOM;BO ...
- Nivo Slider - 世界上最棒的 jQuery 图片轮播插件
Nivo Slider 号称世界上最棒的图片轮播插件,有独立的 jQuery 插件和 WordPress 插件两个版本.目前下载量已经突破 1,800,000 次!jQuery 独立版本的插件主要有如 ...
- 带给你灵感:30个超棒的 SVG 动画展示【上篇】
前端开发人员和设计师一般使用 CSS 来创建 HTML 元素动画.然而,由于 HTML 在创建图案,形状,和其他方面的局限性,它们自然的转向了 SVG,它提供了更多更有趣的能力.借助SVG,我们有更多 ...
- 20个基于 WordPress 搭建的精美网站
WordPress 无处不在,小到人博客,大到广受欢迎的各类特色网站,你都能发现 WordPress 的影子,因为它是创建和维护一个网站最容易使用的平台. 另外,网络上有很多资源来创建你的网站,你基本 ...
- Onsen UI – 新鲜出炉的 PhoneGap 界面框架
Onsen UI 是一个基于元素自定义的 HTML5 UI 框架,用于构建你的移动前端.这个一个基于 Web 组件的概念的框架,让构建应用程序变得更加轻松.Onsen UI 专门针对 PhoneGap ...
- JavaScript学习笔记-正则表达式(语法篇)
正则表达式的模式规则是由一个字符系列组成的,包括所有字母和数字在内;大多数的字符(所有字母和数字)都是按字符的直接量来描述带匹配的字符;一些具有特殊语义的字符按照其特殊语义来进行匹配,有些字符需要通过 ...
- 【转】SharePoint camel query查询 event 或者Calendar 日历列表的时候,怎么查询所有的重复发生的事件
When you query a SharePoint calendar your results will contain: All non-recurring events The first e ...
- [转]很详细的devexpress应用案例
很详细的devexpress应用案例,留着以后参考. 注:转载自http://***/zh-CN/App/Feature.aspx?AppId=50021 UPMS(User Permissions ...