/// <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. 《第一行代码》学习笔记——第1章 开始启程,你的第一行Android代码

    1.3 创建你的第一个Android项目 1.3.1 创建HelloWorld项目 1.Application Name代表应用名称,手机上显示的就是它: 2.Project Name代表项目名称,其 ...

  2. python 三级菜单

    三级列表: menu = { '北京':{ '海淀':{ '五道口':{ 'soho':{}, '网易':{}, 'google':{} }, '中关村':{ '爱奇艺':{}, '汽车之家':{}, ...

  3. 每天一命令 git stash

    git stash  命令是用于保存当前进度的命令.该命令会保存当前工作区的改动.保存的改动是已经跟踪的文件的改动,对于未跟踪的改动stash是不会保存的. git stash 命令常用于分支切换的 ...

  4. java 字符串zlib压缩/解压

    今天在测公司的中间件时发现,增加netty自带的zlib codec压缩处理后,就报decompress failed, invalid head之类的异常.后来发现,直接用bytebuf处理报文体是 ...

  5. [ASP.NET MVC] 使用CLK.AspNet.Identity提供依权限显示选单项目的功能

    [ASP.NET MVC] 使用CLK.AspNet.Identity提供依权限显示选单项目的功能 CLK.AspNet.Identity CLK.AspNet.Identity是一个基于ASP.NE ...

  6. KnockoutJS---一个极其优秀的MVVM模型的js框架

    相信对于DotNet平台的开发人员来讲,MVVM模式已经不再是个陌生的词汇了吧.而我们今天介绍的Knockout JS, 则是一个MVVM模式的JS框架,官方网址:http://knockoutjs. ...

  7. 微信 小程序 drawImage wx.canvasToTempFilePath wx.saveFile 获取设备宽高 尺寸问题

    以下问题测试环境为微信开发者0.10.102800,手机端iphone6,如有不对敬谢指出. 根据我的测试,context.drawImage,在开发者工具中并不能画出来,只有预览到手机中显示. wx ...

  8. animate 实现滑动切换效果

    今天和大家分享一下用 animate 实现滑动切换效果的小例子 ------- 来自<一只有梦想的前端小白> 大家都知道jQuery 提供的有一下几种方法能够实现滑动效果: slideDo ...

  9. 代码创建storyboard

    代码创建storyboard方式如下 // 加载storyboard UIStoryboard *storyboard = [UIStoryboard StoryboardWithName:@&quo ...

  10. Android 使用xml序列化器生成xml文件

    在<Android 生成xml文件>一文中使用流的形式写入xml格式文件,但是存在一定的问题,那就是在短信内容中不能出现<>之类的括号,本文使用xml序列化器来解决 xml序列 ...