Method of Obtaining IIS Site and Virtual Directory Information by C Implementation

  • 2021-08-12 03:21:42
  • OfStack

In this paper, an example of C # implementation to obtain IIS site and virtual directory information method. Share it for your reference. The details are as follows:


using System;
using System.DirectoryServices;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      DirectoryEntry rootEntry = new DirectoryEntry("IIS://localhost/w3svc");
      int siteID = 1;
      foreach (DirectoryEntry entry in rootEntry.Children)
      {
        if (entry.SchemaClassName.Equals("IIsWebServer", StringComparison.OrdinalIgnoreCase))
        {
          Console.WriteLine("Name: {0}", entry.Name);
          Console.WriteLine("Path: {0}", IISWorker.GetWebsitePhysicalPath(entry));
          Console.WriteLine("ServerBindings: {0}", entry.Properties["ServerBindings"].Value);
          Console.WriteLine();
          DirectoryEntry virEntry = new DirectoryEntry(entry.Path + "/ROOT");
          foreach (DirectoryEntry entryVirtual in virEntry.Children)
          {
            if (entryVirtual.SchemaClassName.Equals("IIsWebVirtualDir", StringComparison.OrdinalIgnoreCase))
            {
              Console.WriteLine("SchemaClassName: {0}", entryVirtual.SchemaClassName);
              Console.WriteLine("Name: {0}", entryVirtual.Name);
              Console.WriteLine("Path: {0}", entryVirtual.Properties["Path"].Value);
              Console.WriteLine();
            }
          }
          int ID = Convert.ToInt32(entry.Name);
          if (ID >= siteID)
          {
            siteID = ID + 1;
          }
        }
      }
    }
  }
  public class IISWorker
  {
    /// <summary>
    ///  Get the physical path of the website 
    /// </summary>
    /// <param name="rootEntry"> Web site node </param>
    /// <returns></returns>
    public static string GetWebsitePhysicalPath(DirectoryEntry rootEntry)
    {
      string physicalPath = "";
      foreach (DirectoryEntry childEntry in rootEntry.Children)
      {
        if ((childEntry.SchemaClassName == "IIsWebVirtualDir") && (childEntry.Name.ToLower() == "root"))
        {
          if (childEntry.Properties["Path"].Value != null)
          {
            physicalPath = childEntry.Properties["Path"].Value.ToString();
          }
          else
          {
            physicalPath = "";
          }
        }
      }
      return physicalPath;
    }
  }
}

I hope this article is helpful to everyone's C # programming.


Related articles: