check the status of IIS Application Pool
<p>I am developing a windows service which will gets the IIS Application Pool status  information in every 5 min and stored in database or text file ... like running or stopped.</p>

<p><strong>Getting below exception message:</strong></p>

<blockquote>
  <p>An exception of type 'System.UnauthorizedAccessException' occurred in Microsoft.Web.Administration.dll but was not handled in user code  Additional information: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))</p>
</blockquote>

<p><strong>Below is the code I have tried:</strong></p>

<pre><code> static void Main(string[] args)
    {
        const double interval60Minutes = 5 * 5 * 1000; // milliseconds to one hour
        Timer checkForTime = new Timer(interval60Minutes);
        checkForTime.Elapsed += new ElapsedEventHandler(checkForTime_Elapsed);
        checkForTime.Enabled = true;
        Console.WriteLine("Waiting..");           
        Console.ReadLine();          
    }

    public static void checkForTime_Elapsed(object sender, ElapsedEventArgs e)
    {            
        GetApplicationPoolNames();
    }       

    public static string GetApplicationPoolNames()
    {
        ServerManager manager = new ServerManager();
        string status;
        //string DefaultSiteName = System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName();
        //Site defaultSite = manager.Sites[DefaultSiteName];
        string appVirtaulPath = HttpRuntime.AppDomainAppVirtualPath;
        string mname = System.Environment.MachineName;
        string appPoolName = string.Empty;
        manager = ServerManager.OpenRemote(mname);
        ObjectState result = ObjectState.Unknown;

        ApplicationPoolCollection applicationPoolCollection = manager.ApplicationPools;

        foreach (ApplicationPool applicationPool in applicationPoolCollection)
        {
            //result = manager.ApplicationPools[appPoolName].State;
            result = applicationPool.State;  *// here exception occures*
            Console.WriteLine("State : " + result);
            Console.ReadLine();
        }
   }
</code></pre>

<p>What is wrong in the code? If there are any other ways to achieve this please provide as that will also help me to understand the main cause of exception message.</p>

<p>Any help is appreciated.</p>

<p>Thanks. </p>