Categories
csharp

How to recycle IIS AppPools in Asp.net programmatically

Method to recycle IIS AppPool using c# code. There are several methods but for me this is best one.

Many time we need to recycle asp.net apppool in IIS. This can be done in different way like using DirectoryEntry with AppPool id or by changing last write time of web.config. Here is one function to recycle IIS AppPool using these two methods.

/// <summary>
/// Recycle app pool
/// </summary>
public static bool RecycleIIS()
{
    try
    {
        var poolId = HttpContext.Current.Request.ServerVariables["APP_POOL_ID"];
        var poolPath = @"IIS://" + Environment.MachineName + "/W3SVC/AppPools/" + poolId;

        using (var appPool = new DirectoryEntry(poolPath))
        {
            appPool.Invoke("Recycle", null);
        }
        return true;
    }
    catch { }

    //try
    //{
    //    HttpRuntime.UnloadAppDomain();
    //    return true;
    //}
    //catch { }

    //try
    //{
    //    Process.GetCurrentProcess().Kill();
    //    return true;
    //}
    //catch { }

    string webConfigPath = HttpContext.Current.Request.PhysicalApplicationPath + "\\web.config";
    try
    {
        File.SetLastWriteTimeUtc(webConfigPath, DateTime.UtcNow);
        return true;
    }
    catch (Exception ex)
    {
        Log("Utils.Recycle() : " + ex.Message);
    }
    return false;
}