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 => x.Name == 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 => 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[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 = 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[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 = 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 = 0;
            int maxCount = 4;
            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(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 => 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(0, 3);
                    _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;
            }
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM