2014-09-04 35 views
7

我想通過我的應用程序回收應用程序池。如何通過代碼獲取應用程序池名稱(C#,ASP.net)

此前我將應用程序池名稱存儲在我的數據庫中並使用它進行回收。 但過去發生的情況是,我們將應用程序從一個應用程序池移到另一個應用程序池,有時我們忘記更新數據庫中的應用程序池名稱。

所以我想通過應用程序獲取應用程序池名稱並將其用於回收。

+0

這樣的事情? http://stackoverflow.com/questions/1400464/enumerating-application-pools-in-iis – fuchs777 2014-09-04 11:42:48

回答

12

修改版本的@Razon回答:)

public static string GetCurrentApplicationPoolName() 
    { 
     ServerManager manager = new ServerManager(); 
     string DefaultSiteName = System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName(); 
     Site defaultSite = manager.Sites[DefaultSiteName]; 
     string appVirtualPath = HttpRuntime.AppDomainAppVirtualPath; 

     string appPoolName = string.Empty; 
     foreach (Application app in defaultSite.Applications) 
     { 
      string appPath = app.Path; 
      if (appPath == appVirtualPath) 
      { 
       appPoolName = app.ApplicationPoolName; 
      } 
     } 
     return appPoolName; 
    } 
+1

恕我直言,更好的答案比拉索答案 – Kiquenet 2016-02-04 13:35:21

+0

結合鏈接代碼和那應該是答案。 – Rexxo 2016-02-05 15:59:00

+0

注意:如果您的IIS上的AppPool中的「加載用戶配置文件」設置未設置爲「True」,則此代碼可能會拋出COM異常 – 2018-02-19 23:56:24

7

在很多情況下,它可能足以只讀從環境變量的應用程序池的名稱:

var apppool = System.Environment.GetEnvironmentVariable(
        "APP_POOL_ID", EnvironmentVariableTarget.Process); 
相關問題