C# 启动/停止IIS应用程序池

C# 启动/停止IIS应用程序池,c#,iis,restart,recycle,C#,Iis,Restart,Recycle,我发现这个代码: using System.DirectoryServices; ... void Recycle(string appPool) { string appPoolPath = "IIS://servername/W3SVC/AppPools/" + appPool; using (DirectoryEntry appPoolEntry = new DirectoryEntry(appPoolPath)) { appPoolEntry

我发现这个代码:

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();
    }
}
但当我尝试使用此代码时,出现以下错误:

调用的目标在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();

请提供完整的stacktrace。这是我在日志中看到的全部内容:(我想这是因为我没有某些指定的权限。我有“权限不足”,我需要什么权限?如何添加它?消息:Filename:redirection.config错误:由于权限不足,无法读取配置文件,StackTrace:位于[…]的Microsoft.Web.Administration.Interop.AppHostWritableAdminManager.GetAdminSection(字符串bstrSectionName,字符串bstrSectionPath)Microsoft.Web.Administration.ServerManager.ApplicationPoolCollectionCreator()位于Microsoft.Web.Administration.Lazy.Initialize[T](T&target,CreateInstanceDelegate`1 valueFactory)位于Microsoft.Web.Administration.ServerManager.get\u ApplicationPools()请尝试解决方案。虽然建议MWA是正确的方法,但您还应该指出,这需要管理员权限,而NetworkService不合格。