Dump IIS info with C#

To call the function use:  this.DumpIISInfo(new DirectoryEntry("IIS://localhost/w3svc"));
/// <summary>
        /// Dump iis info
        /// </summary>
        /// <returns>
        /// 0 = All IIS information is written to the console
        /// 1 = Parameter entry was null
        /// </returns>
        public int DumpIISInfo(DirectoryEntry entry)
        {
            if (entry == null) { return 1; }

            foreach (DirectoryEntry childEntry in entry.Children)
            {
                using (childEntry)
                {
                    Console.WriteLine(string.Format("Child name [{0}]", childEntry.Name));
                    foreach (PropertyValueCollection property in childEntry.Properties)
                    {
                        Console.WriteLine(string.Format("[{0}] [{1}] [{2}]", childEntry.Name, property.PropertyName, property.Value));
                    }
                    if (childEntry.Children != null)
                    {
                        this.DumpIISInfo(childEntry);
                    }
                }
            }

            return 0;
        }

Determine if an IIS website or IIS virtualdirectory exist, that run under a given applicationpool, with C#

To call this function use: DoesAppPoolHaveWebsites(new DirectoryEntry(string.Format("IIS://{0}/w3svc", "localhost")), "appPoolName")
 
        /// <summary>
        /// Determine if a IIS website running under an applicationpool exists.
        /// </summary>
        /// <returns></returns>
        public bool DoesAppPoolHaveWebsites(DirectoryEntry iisEntry, string appPoolName)
        {
            bool result = false;
            if (iisEntry == null) { throw new Exception("Parameter [iisEntry] can't be null or empty"); }
            if (string.IsNullOrEmpty(appPoolName)) { throw new Exception("Parameter [appPoolName] can't be null or empty"); }


            foreach (DirectoryEntry child in iisEntry.Children)
            {
                foreach (PropertyValueCollection property in child.Properties)
                {
                    if (property.PropertyName.Equals("AppPoolId", StringComparison.OrdinalIgnoreCase))
                    {
                        if (property.Value != null)
                        {
                            if (property.Value.ToString().Equals(appPoolName, StringComparison.OrdinalIgnoreCase))
                            {
                                result = true;
                                break;
                            }
                        }
                    }
                }
                if (result)
                {
                    break;
                }
                else
                {
                    if (child.Children != null)
                    {
                        if (this.DoesAppPoolHaveWebsites(child, appPoolName))
                        {
                            result = true;
                        }
                    }
                }
            }

            return result;
        }

How to list all IIS applicationpools and properties, with C#

        /// <summary>
        /// List all properties of an IIS applicationpool
        /// </summary>
        /// <param name="serverName">Name of the IIS server e.g. localhost</param>
        /// <param name="appPoolName">Name of the applicationpool e.g. test</param>
        public void ListAppPoolProperties(string serverName, string appPoolName)
        {
            if (string.IsNullOrEmpty(serverName)) { throw new Exception("Parameter [serverName] can't be null or empty"); }
            if (string.IsNullOrEmpty(appPoolName)) { throw new Exception("Parameter [appPoolName] can't be null or empty"); }

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

            foreach (DirectoryEntry site in w3svc.Children)
            {
                Console.WriteLine("Applicationpool");
                foreach (PropertyValueCollection property in site.Properties)
                {
                    Console.WriteLine("Applicationpool Property");
                    Console.WriteLine(string.Format("{0}[{1}]", property.PropertyName, property.Value));
                }

                if (site.Properties["ServerComment"] != null)
                {
                    if (site.Properties["ServerComment"].Value != null)
                    {
                        if (string.Compare(site.Properties["ServerComment"].Value.ToString(), appPoolName, false) == 0)
                        {
                            foreach (DirectoryEntry child in site.Children)
                            {
                                Console.WriteLine("Applicationpool child");
                                foreach (PropertyValueCollection property in child.Properties)
                                {
                                    Console.WriteLine("Applicationpool child property");
                                    Console.WriteLine(string.Format("{0}[{1}]", property.PropertyName, property.Value));
                                }
                            }
                        }
                    }
                }
            }
        }

How to determine if an IIS website contains virtualdirectories, with C#

       /// <summary>
       /// Does the given IIS website contain virtualdirectories.
       /// </summary>
       /// <returns></returns>
       public bool DoesWebsiteContainVirtualDirectories(string website)
       {
           if (string.IsNullOrEmpty(website)) { throw new Exception("Parameter [website] can't be null or empty"); }
           bool result = false;

           DirectoryEntry w3svc = new DirectoryEntry("IIS://localhost/w3svc");

           foreach (DirectoryEntry site in w3svc.Children)
           {
               if (site.Properties["ServerComment"] != null)
               {
                   if (site.Properties["ServerComment"].Value != null)
                   {
                       if (site.SchemaClassName.Equals("IIsWebServer") && site.Properties["ServerComment"].Value.ToString().Equals(website))
                       {
                           foreach (DirectoryEntry child in site.Children)
                           {
                               if (!result)
                               {
                                   foreach (PropertyValueCollection property in child.Properties)
                                   {
                                       if (property.Value != null)
                                       {
                                           if (property.PropertyName.Equals("KeyType") && property.Value.ToString().Equals("IIsWebVirtualDir"))
                                           {
                                               return true;
                                           }
                                       }
                                   }
                               }
                           }
                       }
                   }
               }
           }

           return result;
       }

List all properties of a IIS website, with C#

        /// <summary>
        /// List all properties of a IIS website
        /// </summary>
        /// <param name="serverName">Name of the IIS server e.g. localhost</param>
        /// <param name="websiteName">Name of the website e.g. test</param>
        public void ListWebsiteProperties(string serverName, string websiteName)
        {
            if (string.IsNullOrEmpty(serverName)) { throw new Exception("Parameter [serverName] can't be null or empty"); }
            if (string.IsNullOrEmpty(websiteName)) { throw new Exception("Parameter [websiteName] can't be null or empty"); }

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

            foreach (DirectoryEntry site in w3svc.Children)
            {

                foreach (PropertyValueCollection property in site.Properties)
                {
                    Console.WriteLine(string.Format("{0}[{1}]", property.PropertyName, property.Value));
                }

                if (site.Properties["ServerComment"] != null)
                {
                    if (site.Properties["ServerComment"].Value != null)
                    {
                        if (string.Compare(site.Properties["ServerComment"].Value.ToString(), websiteName, false) == 0)
                        {
                            foreach (DirectoryEntry child in site.Children)
                            {
                                foreach (PropertyValueCollection property in child.Properties)
                                {
                                    Console.WriteLine(string.Format("{0}[{1}]", property.PropertyName, property.Value));
                                }
                            }
                        }
                    }
                }
            }
        }

Get or set the filesystem folder (path) for a IIS website, with C#

        /// <summary>
        /// Get the filesystem folder for the given website
        /// </summary>
        /// <param name="serverName">Name of the IIS server e.g. localhost</param>
        /// <param name="websiteName">Name of the website e.g. test</param>
        /// <returns>filesystem folder or empty if not found</returns>
        public string GetWebSiteFileSystemFolder(string serverName, string websiteName)
        {
            if (string.IsNullOrEmpty(serverName)) { throw new Exception("Parameter [serverName] can't be null or empty"); }
            if (string.IsNullOrEmpty(websiteName)) { throw new Exception("Parameter [websiteName] can't be null or empty"); }
            string result = string.Empty;

            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)
                        {

                            foreach (DirectoryEntry child in site.Children)
                            {
                                if (child.Properties["Path"] != null)
                                {
                                    if (child.Properties["Path"].Value != null)
                                    {
                                        result = child.Properties["Path"].Value.ToString();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return result;
        }
 

Change the Propery “Path” to “ServerBindings” to change serverbindings like “:80:testwebsite”

Get IIS website id on website name, with C#

        /// <summary>
        /// Get website id on websitename
        /// </summary>
        /// <param name="serverName">Name of the IIS server e.g. localhost</param>
        /// <param name="websiteName">Name of the website e.g. test</param>
        /// <returns>
        /// Less the 0, site does not exist
        /// Id of the existing site
        /// </returns>
        public int GetWebSiteId(string serverName, string websiteName)
        {
            int result = -1;

            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 = site.Name;
                            break;
                        }
                    }
                }
            }

            return result;
        }

Check if an IIS website exists with C#

        /// <summary>
        /// Check if a website on the given server exist.
        /// Check on websitename (ServerComment) is case insensitive.
        /// </summary>
        /// <param name="serverName">Name of the IIS server e.g. localhost</param>
        /// <param name="websiteName">Name of the website e.g. test</param>
        /// <returns></returns>
        public bool DoesWebsiteExist(string serverName, string websiteName)
        {
            bool result = false;

            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 = true;
                        }
                    }
                }
            }

            return result;
        }

GetFiles, sorted by Creation DateTime, filtered by include file mask and exclude file mask, including subfolders in C#

The “GetFiles” function, returns all files in the given folder, including subfolders, that match the “includeMask”. The result is sorted by the file CreationTime. The function excludes all files that match the “excludeMask”

 

To call the function:

List<FileInfo> files = FileSystemHelper.GetFiles(@"C:\Windows","*.*", "*.exe", SortOrder.Ascending, SearchOption.AllDirectories);

 

The function:
/// <summary>
///
Get files in a folder sorted by creation datetime and filtered by include mask and exclude mask
/// </summary>
/// <param name=”folder”>
The folder containing the files</param>
/// <param name=”includeMask”>
Include files that meet the given mask</param>
/// <param name=”excludeMask”>
Exclude files that meet the given mask</param>
/// <param name=”sortOrder”>
Sort order, ascending or descending</param>
/// <param name=”searchOption”>
AllDirectories or TopDirectoryOnly</param>
/// <returns></returns>
public staticList<FileInfo> GetFiles(string folder, string includeMask, string excludeMask, SortOrder sortOrder, SearchOption searchOption)
{
    DirectoryInfo folderDirectoryInfo = newDirectoryInfo(folder);
    List<FileInfo> files = newList<FileInfo>(folderDirectoryInfo.GetFiles(includeMask, searchOption));
   
    stringexcludeMaskRegEx = FileSystemHelper.WildcardToRegex(excludeMask);

    // exclude files
  
files = (fromfile infiles
             where!Regex.IsMatch(file.Name, excludeMaskRegEx)
             selectfile).ToList<FileInfo>();

    if(files.Count > 0)
    {
        switch(sortOrder)
        {
            caseSortOrder.Ascending:
                // Sort files oldest first
              
files.Sort(
                    delegate(FileInfo firstFile, FileInfo secondFile)
                    {
                        returnfirstFile.CreationTime.CompareTo(secondFile.CreationTime);
                    }
                );
                break;
            caseSortOrder.Descending:
                // Sort files newest first
              
files.Sort(
                    delegate(FileInfo firstFile, FileInfo secondFile)
                    {
                        returnsecondFile.CreationTime.CompareTo(firstFile.CreationTime);
                    }
                );
                break;
        }

    }

    returnfiles;
}

 

/// <summary>
/// Convert a wildcard mask to regular expression
/// </summary>
/// <param name="pattern">wildcard string</param>
/// <returns>Regular expression string</returns>
public static string WildcardToRegex(string pattern)
{
    return string.Format("^{0}$", Regex.Escape(pattern).Replace("\*", ".*").Replace("\?", "."));
}

public enum SortOrder
{
        Ascending,
        Descending
}