Search code examples
c#iiswebdetectionsuspend

Detect IIS website is suspended


I am currently able to detect whether a IIS Website is started/paused/stopped using the following code:

public int GetWebsiteStatus(string machineName, int websiteId)
{
    DirectoryEntry root = new DirectoryEntry(
        String.Format("IIS://{0}/W3SVC/{1}", machineName, websiteId));
    PropertyValueCollection pvc = root.Properties["ServerState"];
    return pvc.Value
    // - 2: Website Started
    // - 4: Website Stopped
    // - 6: Website Paused
}

I also want to detect if a Website is suspended or not. If the Website is suspended the method above still returns 2 (which is correct) but not enough for me.

I cannot find any code which do the job for IIS6 and higher.


Solution

  • Ah, do you mean the App Pool as stopped because of the timeout configuration? This is a different state to the web site remember? Well, certainly, you could change the settings so it doesn't recycle, but you could also try using code like this;

    First, add a reference to \Windows\System32\inetsrv\Microsoft.Web.Administration.dll, then;

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.Web.Administration;
    namespace MSWebAdmin_Application
    {
        class Program
        {
            static void Main(string[] args)
            {
                ServerManager serverManager = new ServerManager();
                Site site = serverManager.Sites["Default Web Site"];
    
                // get the app for this site
                var appName = site.Applications[0].ApplicationPoolName;
                ApplicationPool appPool = serverManager.ApplicationPools[appName];
    
                Console.WriteLine("Site state is : {0}", site.State);
                Console.WriteLine("App '{0}' state is : {1}", appName, appPool.State);
    
                if (appPool.State == ObjectState.Stopped)
                {
                    // do something because the web site is "suspended"
                }
            }
        }
    }
    

    That code will independantly check the state of your appPool as opposed to your web site. It's possible for the web site to return "started" and the appPool to return "stopped".

    See if it works in your case.