首先 C# 操作 站点 需要 引用Microsoft.Web.Administration.dll 文件,创建站点我们一般需要 远程服务的IP,网站名称、端口、物理路径;这里默认网站名称和应用程序池名称一致。

应用程序池默认不启动,应为刚创建站点是没有对应真实的物理文件,修改 队列长度、启动模式、回收时间、最大工作进程, 以及日志路径。修改的时候如果修改站点物理路径的话,我们需要把文件 从旧得目录拷贝到新的目录下,删除站点就比较简单了。

但是站点应用程序池的停止 和启动就比较难搞了,不是调用stop后就马上能停止的,我们需要一个检测状态的机制以及重试机制,如果没有停止 就等待一段时间,因为只有应用程序池完全停止后我们在可以拷贝文件到应用程序目录下;启动也是一样的需要一个 等待 和重试的机制。相关code如下:

  #region IIS 操作
/// <summary>
/// 创建IIS site
/// </summary>
/// <param name="serverIP">服务器IP</param>
/// <param name="webName">site 名称</param>
/// <param name="port">site端口</param>
/// <param name="path">site地址</param>
void CreateWebSite(string serverIP, string webName, int port, string path)
{
using (ServerManager sm = ServerManager.OpenRemote(serverIP))
{
//创建应用程序池
ApplicationPool appPool = sm.ApplicationPools.FirstOrDefault(x => x.Name == webName);
if (appPool == null)
{
appPool = sm.ApplicationPools.Add(webName);
appPool.AutoStart = false; appPool.QueueLength = ;
appPool.StartMode = StartMode.AlwaysRunning;//启动模式
appPool.Recycling.PeriodicRestart.Time = new TimeSpan();//回收时间间隔
appPool.ProcessModel.IdleTimeout = new TimeSpan();//闲置超时
appPool.ProcessModel.MaxProcesses = ;//最大工作进程数
}
//创建Site
Site site = sm.Sites.FirstOrDefault(x => x.Name == webName);
if (site == null)
{
//检查远程文件夹是否存在 不存在创建
string remotePath = PathUtil.GetRemotePath(serverIP, path);
if (!Directory.Exists(remotePath))
{
Directory.CreateDirectory(remotePath);
} site = sm.Sites.Add(webName, path, port);
site.ServerAutoStart = true; site.Bindings[].EndPoint.Port = port;
Application root = site.Applications["/"];
root.ApplicationPoolName = webName;
root.VirtualDirectories["/"].PhysicalPath = path;
root.SetAttributeValue("preloadEnabled", true); /*预加载*/ #region 修改日志路径
if (!string.IsNullOrEmpty(ConfigUtil.IISLog))
{
string remoteLog = PathUtil.GetRemotePath(serverIP, ConfigUtil.IISLog);
if (!Directory.Exists(remoteLog))
{
Directory.CreateDirectory(remoteLog);
}
site.LogFile.Directory = ConfigUtil.IISLog;
string failedLog = Path.Combine(ConfigUtil.IISLog, "FailedReqLogFiles");
if (!Directory.Exists(failedLog))
{
Directory.CreateDirectory(failedLog);
}
site.TraceFailedRequestsLogging.Directory = failedLog;
}
#endregion
}
sm.CommitChanges();
}
} /// <summary>
/// 修改IIS站点名 端口 和路径
/// </summary>
/// <param name="serverIP">服务器IP</param>
/// <param name="oldWebName">旧的名称</param>
/// <param name="newWebName">新的web名称</param>
/// <param name="newPort">新的端口</param>
/// <param name="newPath">新的路径</param>
void ModifyWebSite(string serverIP, string oldWebName, string newWebName, int newPort, string newPath)
{
using (ServerManager sm = ServerManager.OpenRemote(serverIP))
{
//修改应用程序池
ApplicationPool appPool = sm.ApplicationPools.FirstOrDefault(x => x.Name == oldWebName);
if (appPool != null && oldWebName != newWebName)
{
appPool.Name = newWebName;
}
//修改Site
Site site = sm.Sites.FirstOrDefault(x => x.Name == oldWebName);
if (site != null)
{
Application root = site.Applications["/"];
if (oldWebName != newWebName)
{
site.Name = newWebName;
root.ApplicationPoolName = newWebName;
} int oldPort = site.Bindings[].EndPoint.Port;
if (oldPort != newPort)
{

var binding = site.Bindings[0];
site.Bindings.RemoveAt(0);
site.Bindings.Add($"*:{newPort}:" + binding.Host, binding.Protocol);

                    }
string oldPath = root.VirtualDirectories["/"].PhysicalPath;
if (oldPath.ToLower() != newPath.ToLower())
{
string remoteOldPath = PathUtil.GetRemotePath(serverIP, oldPath);
string remoteNewPath = PathUtil.GetRemotePath(serverIP, newPath);
if (!Directory.Exists(remoteNewPath))
{
Directory.CreateDirectory(remoteNewPath);
} //拷贝文件
CopyFiles(remoteOldPath, remoteNewPath); if (Directory.Exists(remoteOldPath))
{
Directory.Delete(remoteOldPath, true);
}
root.VirtualDirectories["/"].PhysicalPath = newPath;
}
}
#region 修改日志路径
if (!string.IsNullOrEmpty(ConfigUtil.IISLog))
{
string remoteLog = PathUtil.GetRemotePath(serverIP, ConfigUtil.IISLog);
if (!Directory.Exists(remoteLog))
{
Directory.CreateDirectory(remoteLog);
}
site.LogFile.Directory = ConfigUtil.IISLog;
string failedLog = Path.Combine(ConfigUtil.IISLog, "FailedReqLogFiles");
if (!Directory.Exists(failedLog))
{
Directory.CreateDirectory(failedLog);
}
site.TraceFailedRequestsLogging.Directory = failedLog;
}
#endregion
sm.CommitChanges();
}
} /// <summary>
/// 删除IIS 站点
/// </summary>
/// <param name="serverIP">服务器地址</param>
/// <param name="webName">站点名</param>
void RemoveWebSite(string serverIP, string webName)
{ string path = string.Empty;
using (ServerManager sm = ServerManager.OpenRemote(serverIP))
{
//删除应用程序池
ApplicationPool appPool = sm.ApplicationPools.FirstOrDefault(x => x.Name == webName);
if (appPool != null)
{
//appPool.Stop();
sm.ApplicationPools.Remove(appPool);
}
//删除Site
Site site = sm.Sites.FirstOrDefault(x => x.Name == webName);
if (site != null)
{
path = site.Applications["/"].VirtualDirectories["/"].PhysicalPath;
sm.Sites.Remove(site);
}
sm.CommitChanges();
}
//删除文件
if (!string.IsNullOrEmpty(path))
{
string remotePath = PathUtil.GetRemotePath(serverIP, path);
if (Directory.Exists(remotePath))
{
Directory.Delete(remotePath, true);
}
}
} /// <summary>
/// 在服务器上检查端口是否被其他站点使用
/// </summary>
/// <param name="webIP">服务器地址</param>
/// <param name="port">端口号</param>
/// <param name="webName">站点名</param>
/// <returns></returns>
bool CheckPortIsUsed(string webIP, string webName, int webPort)
{
bool exist = false;
try
{
using (ServerManager sm = ServerManager.OpenRemote(webIP))
{
List<Site> sites = sm.Sites.ToList();
foreach (Site site in sites)
{
foreach (var item in site.Bindings)
{
if (item.EndPoint != null && item.EndPoint.Port == webPort && site.Name != webName)
{
exist = true;
break;
}
}//end for Bindings
}//end for Site
}
}
catch (Exception ex)
{
throw ex;
}
return exist;
} /// <summary>
/// 停止或启动应用程序池
/// </summary>
/// <param name="serverIP">远程服务器IP</param>
/// <param name="poolNames">应用程序池名称集合</param>
/// <param name="stop">true 停止 false 启动</param>
public void StopAndStartAppPool(string serverIP, string poolName, bool stop = true)
{
using (ServerManager sm = ServerManager.OpenRemote(serverIP))
{
ApplicationPool pool = sm.ApplicationPools.FirstOrDefault(x => x.Name == poolName);
if (pool != null)
{
StopAndStartAppPool(pool, stop);
if (stop)
{
WaiteAppPoolState(pool, ObjectState.Stopped);
}
}
}
} /// <summary>
/// 停止或启动应用程序池
/// </summary>
/// <param name="pool">应用程序池对象</param>
/// <param name="stop">是否是停止</param>
void StopAndStartAppPool(ApplicationPool pool, bool stop = true)
{
Action act = () =>
{
ObjectState poolSate = pool.State;
if (stop && (poolSate == ObjectState.Starting || poolSate == ObjectState.Started))
{
//如果当前应用程序池是启动或者正在启动状态,调用停止方法
pool.Stop();
}
if (!stop && (poolSate == ObjectState.Stopped || poolSate == ObjectState.Stopping))
{
pool.Start();
}
};
int retryCount = ;
int maxCount = ;
while (pool != null && retryCount <= maxCount)
{
try
{
act();
break;
}
catch (Exception ex)
{
retryCount++;
if (retryCount == maxCount)
{
throw new Exception($"{(stop ? "停止" : "启动")}启动应用程序池{pool.Name}出错{ex.Message}");
}
Thread.Sleep( * );
}
}//end while
} /// <summary>
/// 检查引用程序池的状态
/// </summary>
/// <param name="pool">程序池</param>
/// <param name="state">状态</param>
void WaiteAppPoolState(ApplicationPool pool, ObjectState state)
{
int times = ;
while (pool.State != state && times < /*5分钟*/)
{
//检查应用程序池是否已经停止
Thread.Sleep( * );
times++;
}
} /// <summary>
/// 获取应用程序池 和站点的状态
/// </summary>
/// <param name="serverIP">服务器IP</param>
/// <param name="webName">站点名称</param>
/// <returns></returns>
string GetWebState(string serverIP, string webName)
{
ObjectState poolState = ObjectState.Unknown;
ObjectState siteState = ObjectState.Unknown;
using (ServerManager sm = ServerManager.OpenRemote(serverIP))
{
//应用程序池
ApplicationPool appPool = sm.ApplicationPools.FirstOrDefault(x => x.Name == webName);
if (appPool != null)
{
poolState = appPool.State;
} //Site
Site site = sm.Sites.FirstOrDefault(x => x.Name == webName);
if (site != null)
{
siteState = site.State;
}
}
return $"{poolState.ToString()} | {siteState.ToString()}";
}
#endregion
 public class ConfigUtil
{
static string _dotNetPath = string.Empty;
public static string DotNetPath
{
get
{
if (string.IsNullOrEmpty(_dotNetPath))
{
string sysDisk = Environment.SystemDirectory.Substring(, );
_dotNetPath = sysDisk + @"WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe";//因为当前用的是4.0的环境
}
return _dotNetPath;
}
} static string _iisLog = string.Empty;
public static string IISLog
{
get
{
if (string.IsNullOrEmpty(_iisLog))
{
_iisLog = ConfigurationManager.AppSettings["IISLog"];
}
return _iisLog;
}
}
}

C# 远程服务器 创建、修改、删除 应用程序池 网站的更多相关文章

  1. MySQL进阶11--DDL数据库定义语言--库创建/修改/删除--表的创建/修改/删除/复制

    /*进阶 11 DDL 数据库定义语言 库和表的管理 一:库的管理:创建/修改/删除 二:表的管理:创建/修改/删除 创建: CREATE DATABASE [IF NOT EXISTS] 库名; 修 ...

  2. Linux创建修改删除用户和组

    Linux 创建修改删除用户和组 介绍 在日常的维护过程中创建用户操作用的相对会多一些,但是在这个过程中涉及到的知识点就不单单就是useradd了,接下来就来详细了解账号管理的相关信息. 用户信息 先 ...

  3. oracle11g创建修改删除表

    oracle11g创建修改删除表 我的数据库名字: ORCL         密码:123456 1.模式 2.创建表 3.表约束 4.修改表 5.删除表 1.模式 set oracle_sid=OR ...

  4. git 远程服务器创建项目自动化部署、克隆推送免密码

    1.用git用户 在git目录下 创建裸仓库 git init --bare project_01.git 2.在裸仓库的 hooks目录下创建 post-receive 文件775 3.post-r ...

  5. Linux基础学习-用户的创建修改删除

    用户添加修改删除 1 useradd添加用户 添加一个新用户hehe,指定uid为3000,家目录为/home/haha [root@qdlinux ~]# useradd -u 3000 -d /h ...

  6. Linux 创建修改删除用户和组

    200 ? "200px" : this.width)!important;} --> 介绍 在日常的维护过程中创建用户操作用的相对会多一些,但是在这个过程中涉及到的知识点就 ...

  7. ElasticSearch.net NEST批量创建修改删除索引完整示例

    本示例采用Elasticsearch+Nest 网上查了很多资料,发现用C#调用Elasticsearch搜索引擎的功能代码很分散,功能不完整,多半是非常简单的操作,没有成型的应用示例.比如新增或修改 ...

  8. MySQL入门很简单: 4 创建 修改删除表

    1. 创建表的方法 1)创建表的语法形式 首先,选择数据库: USE 数据库名: 创建表: CREATE TABLE 表名 (属性名 数据类型 [完整性约束条件], 属性名 数据类型 [完整性约束条件 ...

  9. SQL Server 创建 修改 删除数据表

    1. 图形界面方式操作数据表 (1)创建和修改数据表 列名中如果有两个以上单词时,最好用下划线连接,否则可能会给将来的查询维护带来不便.我们公司美国佬做的数据库就很烦,所有列名都有空格,一旦忘记用方括 ...

随机推荐

  1. ubuntu 语言设置

    1.ubuntu ibus 输入法无法切换拼音 原因未安装中文输入法 sudo apt install ibus-pinyin //安装pinyinwin + space(空格) 切换中文输入法 再用 ...

  2. 08 IO库

    #include<iostream> #include<vector> #include<string> #include<fstream> using ...

  3. WebApi的调用-3.Basic验证

    webapi里的特性 /// <summary> /// Basic验证 /// </summary> /// <remarks> /// /// </rem ...

  4. .NetCore源码阅读笔记系列之Security (三) Authentication & AddOpenIdConnect

    通过第二篇文章我们已经知道了授权的内部实现通过自定义的授权Handler来的,同样的道理 OpenIdConnect 同样是通过 OpenIdConnectHandler来请求授权的 那么它内部又是怎 ...

  5. SpringBank 开发日志 Mybatis 使用redis 作为二级缓存时,无法通过cacheEnabled=false 将其关闭

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC ...

  6. #13【BZOJ2794】[Poi2012]Cloakroom

    题解: 感觉真是很智障..连这么简单的题都没想出来 一直在想这么做动态背包..发现不会 首先显然我们将询问按照m 序列按照a[i]排序 然后怎么满足b呢 其实很简单啊..只需要记录f[i]表示前面这些 ...

  7. C# 使用委托实现多线程调用窗体的四种方式

    1.方法一:使用线程 功能描述:在用c#做WinFrom开发的过程中.我们经常需要用到进度条(ProgressBar)用于显示进度信息.这时候我们可能就需要用到多线程,如果不采用多线程控制进度条,窗口 ...

  8. 2018年商业版idea破解安装介绍

    1. IntelliJ IDEA 2018商业版-安装 首先去官网http://www.jetbrains.com/idea/download/#section=windows下载Ultimate版( ...

  9. Strom在本地运行调试出现的错误

    1.错误日志 31385 [main] WARN backtype.storm.daemon.nimbus - Topology submission exception. (topology nam ...

  10. 070 关于HBase的概述

    1.hbase的特点 ->数据存储量可以达到亿级别数据维持在秒级 ->按列存储的数据库 ->能够存储上百万列 ->hbase的底层存储依赖于HDFS ->如何扩展hbas ...