C#远程服务器创建、修改、删除应用程序池网站

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C#远程服务器创建、修改、删除应⽤程序池⽹站
⾸先 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 => == webName);
if (appPool == null)
{
appPool = sm.ApplicationPools.Add(webName);
appPool.AutoStart = false;
appPool.QueueLength = 10000;
appPool.StartMode = StartMode.AlwaysRunning;//启动模式
appPool.Recycling.PeriodicRestart.Time = new TimeSpan();//回收时间间隔
appPool.ProcessModel.IdleTimeout = new TimeSpan();//闲置超时
appPool.ProcessModel.MaxProcesses = 1;//最⼤⼯作进程数
}
//创建Site
Site site = sm.Sites.FirstOrDefault(x => == 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[0].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 = bine(ConfigUtil.IISLog, "FailedReqLogFiles");
if (!Directory.Exists(failedLog))
{
Directory.CreateDirectory(failedLog);
}
site.TraceFailedRequestsLogging.Directory = failedLog;
}
#endregion
}
mitChanges();
}
}
///<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 => == oldWebName);
if (appPool != null && oldWebName != newWebName)
{
= newWebName;
}
//修改Site
Site site = sm.Sites.FirstOrDefault(x => == oldWebName);
if (site != null)
{
Application root = site.Applications["/"];
if (oldWebName != newWebName)
{
= newWebName;
root.ApplicationPoolName = newWebName;
}
int oldPort = site.Bindings[0].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 = bine(ConfigUtil.IISLog, "FailedReqLogFiles");
if (!Directory.Exists(failedLog))
{
Directory.CreateDirectory(failedLog);
}
site.TraceFailedRequestsLogging.Directory = failedLog;
}
#endregion
mitChanges();
}
}
///<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 => == webName);
if (appPool != null)
{
//appPool.Stop();
sm.ApplicationPools.Remove(appPool);
}
//删除Site
Site site = sm.Sites.FirstOrDefault(x => == webName);
if (site != null)
{
path = site.Applications["/"].VirtualDirectories["/"].PhysicalPath;
sm.Sites.Remove(site);
}
mitChanges();
}
//删除⽂件
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 && != 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 => == 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 = 0;
int maxCount = 4;
while (pool != null && retryCount <= maxCount)
{
try
{
act();
break;
}
catch (Exception ex)
{
retryCount++;
if (retryCount == maxCount)
{
throw new Exception($"{(stop ? "停⽌" : "启动")}启动应⽤程序池{}出错{ex.Message}"); }
Thread.Sleep(1000 * 30);
}
}//end while
}
///<summary>
///检查引⽤程序池的状态
///</summary>
///<param name="pool">程序池</param>
///<param name="state">状态</param>
void WaiteAppPoolState(ApplicationPool pool, ObjectState state)
{
int times = 0;
while (pool.State != state && times < 50/*5分钟*/)
{
//检查应⽤程序池是否已经停⽌
Thread.Sleep(1000 * 10);
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 => == webName);
if (appPool != null)
{
poolState = appPool.State;
}
//Site
Site site = sm.Sites.FirstOrDefault(x => == 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(0, 3);
_dotNetPath = sysDisk + @"WINDOWS\\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;
}
}
}。

相关文档
最新文档