启动停止 IIS 应用程序池

Start Stop IIS Application Pool

我找到了这段代码:

using System.DirectoryServices;

...

void Recycle(string appPool)
{
    string appPoolPath = "IIS://servername/W3SVC/AppPools/" + appPool;

    using (DirectoryEntry appPoolEntry = new DirectoryEntry(appPoolPath))
    {
        appPoolEntry.Invoke("Recycle", null);
        appPoolEntry.Close();
    }
}

但是当我尝试使用这段代码时出现了这个错误:

Exception has been thrown by the target of an invocation., StackTrace: at System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args)

我做错了什么?
或者如何获取有关我的应用程序池状态的信息,以及如何在没有任何特殊权限的情况下启动和停止我的应用程序池?

我正在使用内置帐户:NetworkService

尝试使用Microsoft.Web.Administration.ServerManager和Microsoft.Web.Administration.ApplicationPool类。

示例:

var serverManager = new ServerManager();
var appPool = serverManager.ApplicationPools.FirstOrDefault(ap => ap.Name.Equals("AppPoolName"));
appPool.Start();