Get Id of a website in IIS-7 and above

1

I am able to get physical path for any website hosted in IIS-7(C:\Windows\System32\inetsrv\config \applicationHost.config) programmatically (C#) by passing ID as a parameter. But to find Id through the code fails for iis7. The error message is

COMException (0x80005000): Unknown error (0x80005000)

which is not getting resolved even after adding Microsoft.Web.Administration assembly (http://cstruter.com/blog/306).

For reference, here is the code I use to get the ID:

    public static  int GetWebSiteId(string serverName, string websiteName)
    {
        int result = 2;

        DirectoryEntry w3svc = new DirectoryEntry(
                            string.Format("IIS://{0}/w3svc", serverName));

        foreach (DirectoryEntry site in w3svc.Children)
        {
            if (site.Properties["ServerComment"] != null)
            {
                if (site.Properties["ServerComment"].Value != null)
                {
                    if       (string.Compare(site.Properties["ServerComment"].Value.ToString(),
                                         websiteName, false) == 0)
                    {
                        result = int.Parse(site.Name);
                        break;
                    }
                }
            }
        }

        return result;
    }
c#
iis-7
asked on Stack Overflow Mar 8, 2014 by shivi • edited Mar 8, 2014 by Paul-Jan

1 Answer

3

Have you tried to use the new ServerManager object (available for IIS 7.0 and up, through Microsoft.Web.Administration)?

Please try using the following snippet:

using (ServerManager serverManager = new ServerManager()) { 

var sites = serverManager.Sites; 
foreach (Site site in sites) 
{ 
  Console.WriteLine(site.Id); 
}

To obtain the ID of one site in particular, LINQ works like a charm.

answered on Stack Overflow Mar 8, 2014 by Paul-Jan • edited Nov 15, 2019 by Paul-Jan

User contributions licensed under CC BY-SA 3.0