2

I found this code:

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();
    }
}

But when I try to use this code I have this error:

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

What I'm doing wrong?
or how can get info about status of my application pool, and how can I start and stop my app pool without any special permissions?

I'am using built-in account: NetworkService

Drakoo
  • 307
  • 1
  • 3
  • 15

1 Answers1

2

Try to use Microsoft.Web.Administration.ServerManager and Microsoft.Web.Administration.ApplicationPool classes.

Example:

var serverManager = new ServerManager();
var appPool = serverManager.ApplicationPools.FirstOrDefault(ap => ap.Name.Equals("AppPoolName"));
appPool.Start();
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Idan Levi
  • 388
  • 3
  • 18
  • I have "Insufficiend Permission", what permission i need? and how can I add it? – Drakoo Apr 05 '18 at 10:00
  • Message: Filename: redirection.config Error: Cannot read configuration file due to insufficient permissions , StackTrace: at Microsoft.Web.Administration.Interop.AppHostWritableAdminManager.GetAdminSection(String bstrSectionName, String bstrSectionPath) at [...]Microsoft.Web.Administration.ServerManager.ApplicationPoolCollectionCreator() at Microsoft.Web.Administration.Lazy.Initialize[T](T& target, CreateInstanceDelegate`1 valueFactory) at Microsoft.Web.Administration.ServerManager.get_ApplicationPools() – Drakoo Apr 05 '18 at 10:07
  • Please try [this](https://stackoverflow.com/a/5615457/6137045) solution. – Idan Levi Apr 05 '18 at 10:23
  • 1
    While suggesting MWA is the right way, you should also point out that such requires administrator permissions, and NetworkService is not qualified. – Lex Li Apr 05 '18 at 15:38