I want to Recycle application pool programmatically after some interval of time. I tried it using 2 methods that are specified below.
1)
    public static void RecycleAppPools()
    {
        ServerManager serverManager = new ServerManager();
        ApplicationPoolCollection appPools = serverManager.ApplicationPools;
        foreach (ApplicationPool ap in appPools)
        {
            //if(ap.Name== System.Security.Principal.WindowsIdentity.GetCurrent().Name)
            ap.Recycle();
        }
    }
The above is throwing exception of "Access denied"
  2) private static void RecycleApplicationPool(string appPoolId)
    {
        string appPoolPath = "IIS://localhost/W3SVC/AppPools/" + appPoolId;
        var appPool = new DirectoryEntry(appPoolPath);
      //  DirectoryEntry appPoolEntry = new DirectoryEntry(appPoolPath);
        appPool.Invoke("Recycle", null);
    }
This above method is throwing exception "System.Runtime.InteropServices.COMException: Unknown error (0x80005000)". Nothing is working for me.
I have given reference to Microsoft.Web.Administration and working on Visual studio 2015 express with framework 4.6.1 and IIS version is 10.0.14393.0
Please help if anyone can. Thanks in advance.