/// <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站点的更多相关文章

  1. C#操作IIS站点 Microsoft.Web.Administration.dll

    利用IIS7自带类库管理IIS现在变的更强大更方便,而完全可以不需要用DirecotryEntry这个类了(网上很多.net管理iis6.0的文章都用到了DirecotryEntry这个类 ),Mic ...

  2. C#操作IIS程序池及站点的创建配置

    最近在做一个WEB程序的安装包:对一些操作IIS进行一个简单的总结:主要包括对IIS进行站点的新建以及新建站点的NET版本的选择,还有针对IIS7程序池的托管模式以及版本的操作:首先要对Microso ...

  3. C#操作IIS程序池及站点的创建配置(转)

      原文:http://www.cnblogs.com/wujy/archive/2013/02/28/2937667.html 最近在做一个WEB程序的安装包:对一些操作IIS进行一个简单的总结:主 ...

  4. C# 使用代码来操作 IIS

    由于需要维护网站的时候,可以自动将所有的站点HTTP重定向到指定的静态页面上. 要操作 IIS 主要使用到的是“Microsoft.Web.Administration.dll”. 该类库不可以在引用 ...

  5. C#操作IIS完整解析

    原文:C#操作IIS完整解析 最近在为公司实施做了一个工具,Silverlight部署早已是轻车熟路, 但对于非技术人员来说却很是头疼的一件事,当到现场实施碰到客户情况也各不相同, 急需一个类似系统备 ...

  6. 利用ASP.NET操作IIS (可以制作安装程序)

    很多web安装程序都会在IIS里添加应用程序或者应用程序池,早期用ASP.NET操作IIS非常困难,不过,从7.0开始,微软提供了 Microsoft.Web.Administration 类,可以很 ...

  7. .net 程序 动态 控制IIS 站点域名绑定

    第一步:引用 导入 System.EnterpriseServices及System.DirectoryServices 两个引用 程序引用: using System.DirectoryServic ...

  8. IIS站点报拒绝访问Temporary ASP.NET Files的解决办法

    IIS站点本来运行的好好的,突然就出现了:Temporary ASP.NET Files拒绝访问的问题.遇到此类问题,请逐步排查,定可解决. 原因:Windows操作系统升级导致. 办法: 1.检查C ...

  9. IIS站点工作原理与ASP.NET工作原理

    IIS站点工作原理与ASP.NET工作原理  一.IIS IIS 7.0工作原理图 两种模式: 1.用户模式(User Mode)(运行用户的程序代码.限制在特定的范围内活动.有些操作必须要受到Ker ...

随机推荐

  1. Java并发编程:进程和线程之由来

    Java多线程基础:进程和线程之由来 在前面,已经介绍了Java的基础知识,现在我们来讨论一点稍微难一点的问题:Java并发编程.当然,Java并发编程涉及到很多方面的内容,不是一朝一夕就能够融会贯通 ...

  2. Android总结篇系列:Android广播机制

    1.Android广播机制概述 Android广播分为两个方面:广播发送者和广播接收者,通常情况下,BroadcastReceiver指的就是广播接收者(广播接收器).广播作为Android组件间的通 ...

  3. lodash常用方法1--查询

    1.find var _ = require('lodash'); var user1 = { name: 'zhangsan', height: 180, weight: 120 }; var us ...

  4. 【转】PHP计划任务:如何使用Linux的Crontab执行PHP脚本

    转:https://www.centos.bz/2011/03/auto-run-task-crontab/ 我们的PHP程序有时候需要定时执行,我们可以使用ignore_user_abort函数或是 ...

  5. mongoDB简介

    概述 MongoDB 是一款跨平台.面向文档的数据库.用它创建的数据库可以实现高性能.高可用性,并且能够轻松扩展.MongoDB 的运行方式主要基于两个概念:集合(collection)与文档(doc ...

  6. padding下中英文左右两端对齐

    <!DOCTYPE html> <html> <head> <meta charset='UTF-8'> <title>helo</t ...

  7. C#如何自定义DataGridViewColumn来显示TreeView

    我们可以自定义DataGridView的DataGridViewColumn来实现自定义的列,下面介绍一下如何通过扩展DataGridViewColumn来实现一个TreeViewColumn 1 T ...

  8. 使用 HTML5 Canvas 绘制出惊艳的水滴效果

    HTML5 在不久前正式成为推荐标准,标志着全新的 Web 时代已经来临.在众多 HTML5 特性中,Canvas 元素用于在网页上绘制图形,该元素标签强大之处在于可以直接在 HTML 上进行图形操作 ...

  9. Space.js – HTML 驱动的页面 3D 滚动效果

    为了让我们的信息能够有效地沟通,我们需要创建用户和我们的媒体之间的强有力的联系.今天我们就来探讨在网络上呈现故事的新方法,并为此创造了一个开源和免费使用的 JavaScript 库称为 space.j ...

  10. FROONT – 超棒的可视化响应式网页设计工具

    FROONT 是一个基于 Web 的设计工具,在浏览器中运行,使得各类可视化设计的人员都能进行响应式的网页设计,即使是那些没有任何编码技能的设计师.FROONT 使得响应式网页设计能够可视化操作,能够 ...