Tech Off Thread

4 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Extracting list of web sites from IIS manager

Back to Forum: Tech Off
  • User profile image
    kulkarna

    Hi-

    Anyone has any C# code sample that will extract the list of web sites from IIS manager. My code creates web sites on the fly; I need to beforehand make sure that a web site with the same domain name doesn't already exist.

    Thanks!

  • User profile image
    NuTcAsE

    Use System.DirectoryServices to get the web sites from the IIS metabase. Code below:


    using System;
    using System.DirectoryServices;

    class Program
    {
    public static void Main (string[] args) {

    DirectoryEntry iis = new DirectoryEntry ("IIS://" + Environment.MachineName + "/w3svc");
    foreach (DirectoryEntry site in iis.Children) {
    if (site.SchemaClassName == "IIsWebServer") //Web Sites have the IIsWebServer schema{
    foreach (DirectoryEntry virtualDir in site.Children) {
    if (virtualDir.SchemaClassName == "IIsWebVirtualDir") //Virtual directories have the IIsWebVirtualDir schema{
    Console.WriteLine (virtualDir.Name);
    }
    }

    }
    }
    }
    }

  • User profile image
    kulkarna

    Thanks NuTcAsE!
    I'm stil struggling with the issue as virtualDir.Name from you code yields "Root" for all the web sites listed. I'm trying to extract the domain names for each web site as it appears under "Web Sites" (starting with "Default Web Site") in the IIS Manager.

    I'm thinking that there may be a property for the "site" variable in your code that can yield the domain name

    e.g   string domainName =  site.Properties["Description"].ToString();

    However, there's no such property as Description for the site.

    If you right click on a web site and view the properties then under "Web Site Identification" there's the "Description" for each site. This is exactly what I want to list, but don't know how to grab it from the ADSI variable.

  • User profile image
    kulkarna

    After some minor tweaking of NuTcAsE's code I got the solution:

        public bool DomainExists(string domain)
        {
          try
          {
            DirectoryEntry iis = new DirectoryEntry("IIS://localhost/w3svc");
            foreach(DirectoryEntry site in iis.Children)
            {
              if(site.SchemaClassName == "IIsWebServer")
              {
                if(domain.Equals(site.Properties["ServerComment"].Value.ToString()))
                {
                  return true;
                }
              }
            }

            return false;
          }
          catch(Exception e)
          {
                ...
          }
        }


Conversation locked

This conversation has been locked by the site admins. No new comments can be made.