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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.