How to use ServerManager to read IIS sites, not IIS express, from class library OR how do elevated processes handle class libraries?

Josh picture Josh · Dec 11, 2011 · Viewed 24.3k times · Source

I have some utility methods that use Microsoft.Web.Administration.ServerManager that I've been having some issues with. Use the following dead simple code for illustration purposes.

using(var mgr = new ServerManager())
{
    foreach(var site in mgr.Sites)
    {
        Console.WriteLine(site.Name);
    }
}

If I put that code directly in a console application and run it, it will get and list the IIS express websites. If I run that app from an elevated command prompt, it will list the IIS7 websites. A little inconvenient, but so far so good.

If instead I put that code in a class library that is referenced and called by the console app, it will ALWAYS list the IIS Express sites, even if the console app is elevated.

Google has led me to try the following, with no luck.

//This returns IIS express
var mgr = new ServerManager();
//This returns IIS express
var mgr = ServerManager.OpenRemote(Environment.MachineName);
//This throws an exception
var mgr = new  ServerManager(@"%windir%\system32\inetsrv\config\applicationhost.config");

Evidently I've misunderstood something in the way an "elevated" process runs. Shouldn't everything executing in an elevated process, even code from another dll, be run with elevated rights? Evidently not?

Thanks for the help!

Answer

Carlos Aguilar Mares picture Carlos Aguilar Mares · Dec 12, 2011

Make sure you are adding the reference to the correct Microsoft.Web.Administration, should be v7.0.0.0 that is located under c:\windows\system32\inetsrv\ It looks like you are adding a reference to IIS Express's Microsoft.Web.Administraiton which will give you that behavior