Playing around with IIS Application Pool using C#

Just thought of sharing a some useful IIS App pool functions I wrote long back in C#.  Requirement was to play around with IIS v5.0/6.0 and do all settings dynamically -

Note : You must have administrator priveledge to perform all IIS actions.

Namespace Required

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.IO;
using System.Diagnostics;
using IISOle; // IISOle requires a reference to the Active Directory Services.
using System.Reflection;
using System.Configuration;
using System.Text.RegularExpressions;

Functions

public static bool RecycleAppPool(string serverName, string adminUsername, string adminPassword, string appPoolName)
        {
            DirectoryEntry appPools = new DirectoryEntry("IIS://" + serverName + "/w3svc/apppools", adminUsername, adminPassword);
            bool status = false;
            foreach (DirectoryEntry AppPool in appPools.Children)
            {
                if (appPoolName.Equals(AppPool.Name, StringComparison.OrdinalIgnoreCase))
                {
                    AppPool.Invoke("Recycle", null);
                    status = true;
                    break;
                }
            }
            appPools = null;
            return status;
        }

 

/// <summary>
        /// Creates AppPool
        /// </summary>
        /// <param name="metabasePath"></param>
        /// <param name="appPoolName"></param>
        public static bool CreateAppPool(string metabasePath, string appPoolName)
        {
            //  metabasePath is of the form "IIS://<servername>/W3SVC/AppPools"
            //    for example "IIS://localhost/W3SVC/AppPools"
            //  appPoolName is of the form "<name>", for example, "MyAppPool"
            DirectoryEntry newpool, apppools;
            try
            {
                if (metabasePath.EndsWith("/W3SVC/AppPools"))
                {
                    apppools = new DirectoryEntry(metabasePath);
                    newpool = apppools.Children.Add(appPoolName, "IIsApplicationPool");
                    newpool.CommitChanges();
                    newpool = null;
                    apppools = null;
                    return true;
                }
                else
                    throw new Exception(" Failed in CreateAppPool; application pools can only be created in the */W3SVC/AppPools node.");               
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Failed in CreateAppPool with the following exception: \n{0}", ex.Message));
            }
            finally
            {
                newpool = null;
                apppools = null;
            }
        }

        /// <summary>
        /// Assigns AppPool to Virtual Directory
        /// </summary>
        /// <param name="metabasePath"></param>
        /// <param name="appPoolName"></param>
        public static bool AssignVDirToAppPool(string metabasePath, string appPoolName)
        {
            //  metabasePath is of the form "IIS://<servername>/W3SVC/<siteID>/Root[/<vDir>]"
            //    for example "IIS://localhost/W3SVC/1/Root/MyVDir"
            //  appPoolName is of the form "<name>", for example, "MyAppPool"
            //Console.WriteLine("\nAssigning application {0} to the application pool named {1}:", metabasePath, appPoolName);

            DirectoryEntry vDir = new DirectoryEntry(metabasePath);
            string className = vDir.SchemaClassName.ToString();
            if (className.EndsWith("VirtualDir"))
            {
                object[] param = { 0, appPoolName, true };
                vDir.Invoke("AppCreate3", param);
                vDir.Properties["AppIsolated"][0] = "2";
                vDir = null;
                return true;
            }
            else
                throw new Exception(" Failed in AssignVDirToAppPool; only virtual directories can be assigned to application pools");
        }

 

  /// <summary>
        /// Delete AppPool
        /// </summary>
        /// <param name="metabasePath"></param>
        /// <param name="appPoolName"></param>
        public static bool DeleteAppPool(string serverName, string adminUsername, string adminPassword, string appPoolName)
        {
            //  metabasePath is of the form "IIS://<servername>/W3SVC/AppPools"
            //  for example "IIS://localhost/W3SVC/AppPools"
            //  appPoolName is of the form "<name>", for example, "MyAppPool"

            DirectoryEntry appPools = new DirectoryEntry("IIS://" + serverName + "/w3svc/apppools", adminUsername, adminPassword);
            bool status = false;
            foreach (DirectoryEntry AppPool in appPools.Children)
            {
                if (appPoolName.Equals(AppPool.Name, StringComparison.OrdinalIgnoreCase))
                {
                    AppPool.DeleteTree();
                    status = true;
                    break;
                }
            }
            appPools = null;
            return status;
        }

Hope you folks find it useful. If you need any other help related to IIS, just post me your requirement.

24 Comments

  • This is great....I've been looking for some simple code examples on how to interact with IIS.

    If you've got time...we would like to add and remove IIS host headers for a website. We let our users use their own domain for private label features, but right now it shoots us an email and we have to setup the headers manually on all the web servers in our farm (small farm...but still).

    Everytime we look into automating the processes it appears that the code ends up being very complicated and a little overwhelming, any pointers would be GREATLY appreciated.

  • Sure enjoy - &nbsp;/// &lt;summary&gt;&nbsp;/// Adds a host header value to a specified website. &nbsp;/// &lt;/summary&gt;&nbsp;/// &lt;param name="hostHeader"&gt;The host header. Must be in the form IP:Port:Hostname &lt;/param&gt;&nbsp;/// &lt;param name="websiteID"&gt;The ID of the website the host header should be added to &lt;/param&gt;&nbsp;public static void AddHostHeader(string serverName, string adminUsername, string adminPassword, string websiteName, string hostHeader) &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;string siteID = GetSiteID(serverName, adminUsername, adminPassword, websiteName);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;DirectoryEntry root = new DirectoryEntry("IIS://" + serverName + "/W3SVC/" + siteID, adminUsername, adminPassword);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;PropertyValueCollection serverBindings = root.Properties["ServerBindings"];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//Add the new binding&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;serverBindings.Add(hostHeader);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//Create an object array and copy the content to this array&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Object[] newList = new Object[serverBindings.Count];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;serverBindings.CopyTo(newList, 0);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//Write to metabase&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;root.Properties["ServerBindings"].Value = newList;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;root.CommitChanges();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;root.Close(); root.Dispose();&nbsp;}&nbsp;public static string GetSiteID(string serverName, string adminUsername, string adminPassword, string websiteName)&nbsp;&nbsp;{&nbsp; &nbsp; &nbsp;DirectoryEntry root = new DirectoryEntry("IIS://" + serverName + "/W3SVC", adminUsername, adminPassword);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;string siteID = "0";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;foreach (DirectoryEntry e in root.Children)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if ((e.SchemaClassName == "IIsWebServer") &amp;&amp; (e.Properties["ServerComment"][0].ToString() == websiteName))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;siteID = e.Name;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;root.Close();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;root.Dispose();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return siteID;&nbsp; &nbsp; &nbsp; &nbsp;}
    &nbsp;

  • Thanks a ton!

  • Nice code.
    It can be used to recycle the IIS application pool remotely.

  • .Children.Find(apppool,"IIsApplicationPool").Invoke("Recycle", null);

  • Hi,

    I need a method or script which will help in finding the status of Application Pool and if any specified application pool is in stopped/stuck state that needs to be recycled automatically. Im totally new to IIS.

    If you have any script for this can you please update me. You can contact me at vinay_prasad01@yahoo.co.in

  • Hi... I need to find if an app pool is running before calling Recycle function. How can I check the status of an app pool?

    Thanks for the article... very informative.

  • I inserted your code into a simple test app to create appPools on Server 2008 and it works fine. However, when I insert the same code into our real app it throws a Com exception. Any ideas would be greatly appreciated.

  • Hi all, thanks for this great code,
    another way to assign administrator rights is to use impersonation in web.config.

    Add this in your web.config:



    I have used this code within a web.config on my Webservice dedicated to manage IIS remotly.

    Have fun

  • To use impersonation, dont forget to remove all userName and password entry of the C# code.

    like this:

    public static bool RecycleAppPool(string serverName, string appPoolName)
    {
    DirectoryEntry appPools = new DirectoryEntry("IIS://" + serverName + "/w3svc/apppools");
    bool status = false;
    foreach (DirectoryEntry AppPool in appPools.Children)
    {
    if (appPoolName.Equals(AppPool.Name, StringComparison.OrdinalIgnoreCase))
    {
    AppPool.Invoke("Recycle", null);
    status = true;
    break;
    }
    }
    appPools = null;
    return status;
    }

    Instead of this:

    public static bool RecycleAppPool(string serverName, string adminUsername, string adminPassword, string appPoolName)
    {
    DirectoryEntry appPools = new DirectoryEntry("IIS://" + serverName + "/w3svc/apppools", adminUsername, adminPassword);
    bool status = false;
    foreach (DirectoryEntry AppPool in appPools.Children)
    {
    if (appPoolName.Equals(AppPool.Name, StringComparison.OrdinalIgnoreCase))
    {
    AppPool.Invoke("Recycle", null);
    status = true;
    break;
    }
    }
    appPools = null;
    return status;
    }

  • Excellent article. Thanks.

  • To know the status of Application pool wheter its running or stopped....

    string appPoolName = listAppPool[i].ToString();
    string appPoolPath = @"IIS://" + System.Environment.MachineName + "/W3SVC/AppPools/" + appPoolName;
    //Getting Status of Applicaiton Pools
    try
    {
    DirectoryEntry w3svc = new DirectoryEntry(appPoolPath);
    switch (w3svc.Properties["AppPoolState"].Value)
    {
    case 2:
    Response.Write("Started");
    break;
    case "4":
    Response.Write("Stopped");
    break;
    default:
    Response.Write("UNKNOWN");
    break;
    }
    }
    catch (Exception ex)
    {
    }

  • Murder Her,value media knowledge estimate blow bag human neck confirm large male necessary error head rural good look payment severe conclusion control climb nice within brain fair sell practical direct protect hard expense widely team technique point experience programme may period building eat study wear work before recognition elsewhere flow intention cover entitle total help payment attract yourself plant effort vast doctor plan information point audience actually cost show effect merely deny possible walk award track light approve candidate arrive enemy temperature hospital operation condition help set family supply reveal magazine wash

  • This post could not be more on the money!

  • How to check application pool flag for enable32bitapplication?

  • Hi I am getting some runtime com exeption could you please help

    Thanks

  • Hi,

    I am using C# for recycling apppool on IIS 7.5. But it gives me invalid class.

    I am using following code.

    Get-WmiObject -ComputerName vmstaswfapsys1 -Namespace root\cimv2 -Class ApplicationPool -Authentication 6 -Filter "Name='DefaultAppPool'" |

    Invoke-WmiMethod -Name Recycle

    Please let me know is there any solution for this.

    -Rajiv

  • Hello,

    how I can get number of applications assigned to application pool without checking all sites configured in IIS7.5 using C#?

    Regards

  • It’s best to participate in a contest for among that the best internet sites via
    internet. I’ll advocate this website!

  • I?¦ve recently started a blog, that the information you
    offer on this website has helped me very much. Thanks for all of your time & work.

  • This website is great. I like it.(www.linkspirit.net)N_X_D_S.

  • Great post, I was doing a google search and your site
    came up for foreclosures in Winter Springs, FL conversely anyway, I
    have enjoyed reading it, keep it up!

  • You have to check this out… [...] Wonderful story, reckoned
    we could combine a few unrelated data, nevertheless actually
    worth taking a look, whoa did one find out about Mid East has
    got more problerms as well [...]……

  • This website is great. I like it.(www.linkspirit.net)N_X_D_S.

Comments have been disabled for this content.