How to get Application Pool name through code (C#, ASP.net)

dIvYaNsH sInGh picture dIvYaNsH sInGh · Sep 4, 2014 · Viewed 15.7k times · Source

I want to recycle the application pool through my application.

Previously I was storing the application pool name in my database and using that to recycle. But It happened in the past that we moved apps from one app pool to another and sometimes we forget to update the app pool name in the database.

So I am thinking to get the app pool name through the application and use that for recycling.

Answer

dIvYaNsH sInGh picture dIvYaNsH sInGh · Sep 4, 2014

Modified version of @Razon answer :)

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;
    }