c#操作IIS之IISHelper
//-----------------------------------------------------------------------
// <copyright file="IISHelper.cs" company="MY EXPRESS, Ltd.">
// Copyright (c) 2016 , All rights reserved.
// </copyright>
//----------------------------------------------------------------------- using System;
using Microsoft.Web.Administration; namespace DotNet.MVCInfrastructure.Helpers
{
using DotNet.Utilities; /// <summary>
/// IIS应用
/// Microsoft中提供了管理IIS7的一些非常强大的API——Microsoft.Web.Administration,
/// 可以很方便的让我们以编程的方式管理,设定IIS 7的各项配置。
/// Microsoft.Web.Administration.dll位于IIS的目录(%WinDir%\System32\InetSrv)下,
/// 在项目中添加对其的引用后您就可以使用这些API了
///
///
/// 错误: 由于权限不足而无法读取配置文件 文件名: redirection.config
/// 解决办法 选择该网站的应用程序池的高级设置里进程模型下的标识选择为LocalSystem
///
/// 修改纪录
///
/// 2018-09-10版本:1.0 SongBiao 创建文件。
///
/// <author>
/// <name>SongBiao</name>
/// <date>2018-09-10</date>
/// </author>
/// </summary> public partial class IISHelper
{
/// <summary>
/// 停止一个站点
/// </summary> public static BaseResult StopSite(string site)
{
BaseResult result = BaseResult.Fail("未知错误");
try
{
ServerManager iisManager = new ServerManager();
if (iisManager.Sites[site].State == ObjectState.Stopped || iisManager.Sites[site].State == ObjectState.Stopping)
{
result.Status = true;
result.StatusMessage = site + ":站点已停止";
}
else
{
ObjectState state = iisManager.Sites[site].Stop();
if (state == ObjectState.Stopping || state == ObjectState.Stopped)
{
result.Status = true;
result.StatusMessage = site + ":站点已停止";
}
else
{
result.Status = false;
result.StatusMessage = site + ":站点停止失败";
}
}
}
catch (Exception ex)
{
NLogHelper.Warn(ex, " public static BaseResult StopSite(string site)");
result.Status = false;
result.StatusMessage = site + ":站点停止出现异常:" + ex.Message;
} return result;
} /// <summary>
/// 启动一个站点
/// </summary> public static BaseResult StartSite(string site)
{
BaseResult result = BaseResult.Fail("未知错误");
try
{
ServerManager iisManager = new ServerManager();
if (iisManager.Sites[site].State != ObjectState.Started || iisManager.Sites[site].State != ObjectState.Starting)
{
ObjectState state = iisManager.Sites[site].Start();
if (state == ObjectState.Starting || state == ObjectState.Started)
{
result.Status = true;
result.StatusMessage = site + ":站点已启动";
}
else
{
result.Status = false;
result.StatusMessage = site + ":站点停止失败";
}
}
else
{
result.Status = true;
result.StatusMessage = site + ":站点已是启动状态";
}
}
catch (Exception ex)
{
NLogHelper.Warn(ex, " public static BaseResult StartSite(string site)");
result.Status = false;
result.StatusMessage = site + ":站点停止出现异常:" + ex.Message;
} return result;
} /// <summary>
/// 停止应用程序池
/// </summary>
/// <param name="appPool"></param>
public static BaseResult StopApplicationPool(string appPool = null)
{
BaseResult result = BaseResult.Fail("未知错误");
try
{
if (string.IsNullOrWhiteSpace(appPool))
{
appPool = Environment.GetEnvironmentVariable("APP_POOL_ID", EnvironmentVariableTarget.Process);
}
ServerManager iisManager = new ServerManager();
if (iisManager.ApplicationPools[appPool].State == ObjectState.Stopped || iisManager.ApplicationPools[appPool].State == ObjectState.Stopping)
{
result.Status = true;
result.StatusMessage = appPool + ":应用程序池已停止";
}
else
{
ObjectState state = iisManager.ApplicationPools[appPool].Stop();
if (state == ObjectState.Stopping || state == ObjectState.Stopped)
{
result.Status = true;
result.StatusMessage = appPool + ":应用程序池已停止";
}
else
{
result.Status = false;
result.StatusMessage = appPool + ":应用程序池停止失败,请重试";
}
}
}
catch (Exception ex)
{
NLogHelper.Warn(ex, " public static BaseResult StopApplicationPool(string appPool = null)");
result.Status = false;
result.StatusMessage = appPool + ":应用程序池失败出现异常:" + ex.Message;
} return result;
} /// <summary>
/// 启动应用程序池
/// </summary>
/// <param name="appPool"></param>
public static BaseResult StartApplicationPool(string appPool = null)
{
BaseResult result = BaseResult.Fail("未知错误");
try
{
if (string.IsNullOrWhiteSpace(appPool))
{
appPool = Environment.GetEnvironmentVariable("APP_POOL_ID", EnvironmentVariableTarget.Process);
}
ServerManager iisManager = new ServerManager();
if (iisManager.ApplicationPools[appPool].State != ObjectState.Started || iisManager.ApplicationPools[appPool].State != ObjectState.Starting)
{
ObjectState state = iisManager.ApplicationPools[appPool].Start();
if (state == ObjectState.Starting || state == ObjectState.Started)
{
result.Status = true;
result.StatusMessage = appPool + ":应用程序池已启动";
}
else
{
result.Status = false;
result.StatusMessage = appPool + ":应用程序池启动失败,请重试";
}
}
else
{
result.Status = true;
result.StatusMessage = appPool + ":应用程序池已是启动状态";
}
}
catch (Exception ex)
{
NLogHelper.Warn(ex, " public static BaseResult StartApplicationPool(string appPool = null)");
result.Status = false;
result.StatusMessage = appPool + ":应用程序池启动出现异常:" + ex.Message;
} return result;
} /// <summary>
/// 回收应用程序池
/// </summary>
/// <param name="appPool"></param>
public static BaseResult RecycleApplicationPool(string appPool = null)
{
BaseResult result = BaseResult.Fail("未知错误");
try
{
if (string.IsNullOrWhiteSpace(appPool))
{
appPool = Environment.GetEnvironmentVariable("APP_POOL_ID", EnvironmentVariableTarget.Process);
}
ServerManager iisManager = new ServerManager();
ObjectState state = iisManager.ApplicationPools[appPool].Recycle(); result.Status = true;
result.StatusMessage = appPool + ":应用程序池回收成功:"+ state; }
catch (Exception ex)
{
NLogHelper.Warn(ex, " public static BaseResult StartApplicationPool(string appPool = null)");
result.Status = false;
result.StatusMessage = appPool + ":应用程序池回收出现异常:" + ex.Message;
} return result;
} /// <summary>
/// 运行时控制:得到当前正在处理的请求
/// </summary>
/// <param name="appPool"></param>
public static void GetWorking(string appPool)
{
ServerManager iisManager = new ServerManager();
foreach (WorkerProcess w3wp in iisManager.WorkerProcesses)
{
Console.WriteLine("W3WP ({0})", w3wp.ProcessId);
foreach (Request request in w3wp.GetRequests())
{
Console.WriteLine("{0} - {1},{2},{3}",
request.Url,
request.ClientIPAddr,
request.TimeElapsed,
request.TimeInState);
}
}
} /// <summary>
/// 获取IIS日志文件路径
/// </summary>
/// <returns></returns> public static string GetIISLogPath()
{
ServerManager manager = new ServerManager();
// 获取IIS配置文件:applicationHost.config
var config = manager.GetApplicationHostConfiguration();
var log = config.GetSection("system.applicationHost/log");
var logFile = log.GetChildElement("centralW3CLogFile");
//获取网站日志文件保存路径
var logPath = logFile.GetAttributeValue("directory").ToString();
return logPath;
} /// <summary>
///创建新站点
/// </summary>
/// <param name="siteName"></param>
/// <param name="bindingInfo">"*:<port>:<hostname>" <example>"*:80:myhost.com"</example></param>
/// <param name="physicalPath"></param>
public static void CreateSite(string siteName, string bindingInfo, string physicalPath)
{
createSite(siteName, "http", bindingInfo, physicalPath, true, siteName + "Pool", ProcessModelIdentityType.NetworkService, null, null, ManagedPipelineMode.Integrated, null);
} /// <summary>
/// 创建新站点
/// </summary>
/// <param name="siteName"></param>
/// <param name="protocol"></param>
/// <param name="bindingInformation"></param>
/// <param name="physicalPath"></param>
/// <param name="createAppPool"></param>
/// <param name="appPoolName"></param>
/// <param name="identityType"></param>
/// <param name="appPoolUserName"></param>
/// <param name="appPoolPassword"></param>
/// <param name="appPoolPipelineMode"></param>
/// <param name="managedRuntimeVersion"></param>
private static void 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())
{
Site site = mgr.Sites.Add(siteName, protocol, bindingInformation, 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;
} mgr.CommitChanges();
}
} /// <summary>
/// Delete an existent web site.
/// </summary>
/// <param name="siteName">Site name.</param>
public static void DeleteSite(string siteName)
{
using (ServerManager mgr = new ServerManager())
{
Site site = mgr.Sites[siteName];
if (site != null)
{
mgr.Sites.Remove(site);
mgr.CommitChanges();
}
}
} /// <summary>
/// 创建虚拟目录
/// </summary>
/// <param name="siteName"></param>
/// <param name="vDirName"></param>
/// <param name="physicalPath"></param>
public static void CreateVDir(string siteName, string vDirName, string physicalPath)
{
using (ServerManager mgr = new ServerManager())
{
Site site = mgr.Sites[siteName];
if (site == null)
{
throw new ApplicationException(String.Format("Web site {0} does not exist", siteName));
}
site.Applications.Add("/" + vDirName, physicalPath);
mgr.CommitChanges();
}
} /// <summary>
/// 删除虚拟目录
/// </summary>
/// <param name="siteName"></param>
/// <param name="vDirName"></param>
public static void DeleteVDir(string siteName, string vDirName)
{
using (ServerManager mgr = new ServerManager())
{
Site site = mgr.Sites[siteName];
if (site != null)
{
Microsoft.Web.Administration.Application app = site.Applications["/" + vDirName];
if (app != null)
{
site.Applications.Remove(app);
mgr.CommitChanges();
}
}
}
} /// <summary>
/// Delete an existent web site app pool.
/// </summary>
/// <param name="appPoolName">App pool name for deletion.</param>
public static void DeletePool(string appPoolName)
{
using (ServerManager mgr = new ServerManager())
{
ApplicationPool pool = mgr.ApplicationPools[appPoolName];
if (pool != null)
{
mgr.ApplicationPools.Remove(pool);
mgr.CommitChanges();
}
}
} /// <summary>
/// 在站点上添加默认文档。
/// </summary>
/// <param name="siteName"></param>
/// <param name="defaultDocName"></param>
public static void 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;
}
} try
{
ConfigurationElement docElement = filesCollection.CreateElement();
docElement.SetAttributeValue("value", defaultDocName);
filesCollection.Add(docElement);
}
catch (Exception) { } //this will fail if existing mgr.CommitChanges();
}
} /// <summary>
/// 检查虚拟目录是否存在。
/// </summary>
/// <param name="siteName"></param>
/// <param name="path"></param>
/// <returns></returns> public static bool VerifyVirtualPathIsExist(string siteName, string path)
{
using (ServerManager mgr = new ServerManager())
{
Site site = mgr.Sites[siteName];
if (site != null)
{
foreach (Microsoft.Web.Administration.Application app in site.Applications)
{
if (app.Path.ToUpper().Equals(path.ToUpper()))
{
return true;
}
}
}
} return false;
} /// <summary>
/// 检查站点是否存在。
/// </summary>
/// <param name="siteName"></param>
/// <returns></returns>
public static bool VerifyWebSiteIsExist(string siteName)
{
using (ServerManager mgr = new ServerManager())
{
for (int i = ; i < mgr.Sites.Count; i++)
{
if (mgr.Sites[i].Name.ToUpper().Equals(siteName.ToUpper()))
{
return true;
}
}
} return false;
} /// <summary>
/// 检查Bindings信息。
/// </summary>
/// <param name="bindingInfo"></param>
/// <returns></returns>
public static bool VerifyWebSiteBindingsIsExist(string bindingInfo)
{
string temp = string.Empty;
using (ServerManager mgr = new ServerManager())
{
for (int i = ; i < mgr.Sites.Count; i++)
{
foreach (Microsoft.Web.Administration.Binding b in mgr.Sites[i].Bindings)
{
temp = b.BindingInformation;
if (temp.IndexOf('*') < )
{
temp = "*" + temp;
}
if (temp.Equals(bindingInfo))
{
return true;
}
}
}
} return false;
} }
}
c#操作IIS之IISHelper的更多相关文章
- C#操作IIS程序池及站点的创建配置
最近在做一个WEB程序的安装包:对一些操作IIS进行一个简单的总结:主要包括对IIS进行站点的新建以及新建站点的NET版本的选择,还有针对IIS7程序池的托管模式以及版本的操作:首先要对Microso ...
- C# 使用代码来操作 IIS
由于需要维护网站的时候,可以自动将所有的站点HTTP重定向到指定的静态页面上. 要操作 IIS 主要使用到的是“Microsoft.Web.Administration.dll”. 该类库不可以在引用 ...
- C#操作IIS完整解析
原文:C#操作IIS完整解析 最近在为公司实施做了一个工具,Silverlight部署早已是轻车熟路, 但对于非技术人员来说却很是头疼的一件事,当到现场实施碰到客户情况也各不相同, 急需一个类似系统备 ...
- .net操作IIS,新建网站,新建应用程序池,设置应用程序池版本,设置网站和应用程序池的关联
ServerManager类用来操作IIS,提供了很多操作IIS的API.使用ServerManager必须引用Microsoft.Web.Administration.dll,具体路径为:%wind ...
- 利用ASP.NET操作IIS (可以制作安装程序)
很多web安装程序都会在IIS里添加应用程序或者应用程序池,早期用ASP.NET操作IIS非常困难,不过,从7.0开始,微软提供了 Microsoft.Web.Administration 类,可以很 ...
- C#操作IIS程序池及站点的创建配置(转)
原文:http://www.cnblogs.com/wujy/archive/2013/02/28/2937667.html 最近在做一个WEB程序的安装包:对一些操作IIS进行一个简单的总结:主 ...
- C#操作IIS服务
进入正题:先从使用角度来讲解IIS操作,然后再深入到具体的IIS服务底层原理. [1]前提掌握要点: (1).IIS到目前经历了四个版本分别为 IIS4.0 IIS5.0 IIS6.0 IIS7.0, ...
- IISHelper操作iis
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- c#操作IIS站点
/// <summary> /// 获取本地IIS版本 /// </summary> /// <returns></returns> public st ...
随机推荐
- QT中pro文件编写的详细说明
如果用QTCreator开发的小伙伴,可能都知道.pro文件,但是里面的具体配置可能比较模糊,今天我就来给大家好好讲解下 一.名称解释 QT += :这个是添加QT需要的模块 TARGET = :生成 ...
- linux内核IDR机制详解【转】
这几天在看Linux内核的IPC命名空间时候看到关于IDR的一些管理性质的东西,刚开始看有些迷茫,深入看下去豁然开朗的感觉,把一些心得输出共勉. 我们来看一下什么是IDR?IDR的作用是什么呢? 先来 ...
- 宋宝华:Docker 最初的2小时(Docker从入门到入门)【转】
最初的2小时,你会爱上Docker,对原理和使用流程有个最基本的理解,避免满世界无头苍蝇式找资料.本人反对暴风骤雨式多管齐下狂轰滥炸的学习方式,提倡迭代学习法,就是先知道怎么玩,有个感性认识,再深入学 ...
- c/c++ linux 进程间通信系列5,使用信号量
linux 进程间通信系列5,使用信号量 信号量的工作原理: 由于信号量只能进行两种操作等待和发送信号,即P(sv)和V(sv),他们的行为是这样的: P(sv):如果sv的值大于零,就给它减1:如果 ...
- spark-2.4.0-hadoop2.7-安装部署
1. 主机规划 主机名称 IP地址 操作系统 部署软件 运行进程 备注 mini01 172.16.1.11[内网] 10.0.0.11 [外网] CentOS 7.5 Jdk-8.zookeepe ...
- 解决topjui中工具栏按钮删除刷新从属表
遇到了这么个问题:当在从属datagrid表格中,点击主表工具栏按钮中的删除,通过后台的多表删除的sql,返回给前台之后,从属表的数据成功在数据库中删除,但是在前台页面显示的时候,只刷新了主表,子表未 ...
- RabbitMQ集群搭建和使用
一.环境准备 1.选择RabbitMQ的版本 http://www.rabbitmq.com/changelog.html 注: 不同版本的Linux选择的RabbitMQ版本也不同,参照 http: ...
- RESTful API规范
1. 域名 应该尽量将API部署在专用的域名下. https://api.example.com 如果确定API简单,不会有进一步的括在,可以考虑放在主域名之下. https://example.or ...
- ubuntu系统下mysql重置密码和修改密码操作
一.忘记密码后想重置密码 在介绍修改密码之前,先介绍一个文件/etc/mysql/debian.cnf.其主要内容如下图: 里面有一个debian-sys-maint用户,这个用户只有Debian或U ...
- centos7下kubernetes(16。kubernetes-滚动更新)
滚动更新:一次只更新一小部分副本,成功后,在更新更多的副本,最终完成所有副本的更新. 滚动更新的最大好处是零停机,整个更新过程始终有副本在运行,从而保证了业余的连续性 下面部署三个副本的应用,出事镜像 ...