c#操作IIS之IISHelper
阿新 • • 發佈:2019-01-14
//----------------------------------------------------------------------- // <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(0)) { 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 = 0; 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 = 0; i < mgr.Sites.Count; i++) { foreach (Microsoft.Web.Administration.Binding b in mgr.Sites[i].Bindings) { temp = b.BindingInformation; if (temp.IndexOf('*') < 0) { temp = "*" + temp; } if (temp.Equals(bindingInfo)) { return true; } } } } return false; } } }
來源:https://www.cnblogs.com/hnsongbiao/p/9618954.html