giammin

Recycle ASP.NET Application Pool from within

Mar 14th, 2013
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.04 KB | None | 0 0
  1. /// <summary>
  2. /// Restarts the Web Application
  3. /// Requires either Full Trust (HttpRuntime.UnloadAppDomain)
  4. /// or Write access to web.config.
  5. /// </summary>
  6. public static bool RestartWebApplication()
  7. {
  8.     var logger = LogManager.GetLogger("HttpProsperoApplication.RestartWebApplication");
  9.     bool rtn = false;
  10.     try
  11.     {
  12.         logger.Info("Restarting AppPool with UnloadAppDomain");
  13.         // *** This requires full trust so this will fail in many scenarios
  14.         HttpRuntime.UnloadAppDomain();
  15.         rtn = true;
  16.     }
  17.     catch (Exception ex)
  18.     {
  19.         logger.ErrorException("Cannot recycle AppPool with HttpRuntime.UnloadAppDomain", ex);
  20.         try
  21.         {
  22.             logger.Info("Restarting AppPool modifying web.config");
  23.             // *** Couldn't unload with Runtime - let's try modifying web.config
  24.             string configPath = HttpContext.Current.Server.MapPath(@"~\web.config");
  25.             File.SetLastWriteTimeUtc(configPath, DateTime.UtcNow);
  26.             rtn = true;
  27.         }
  28.         catch (Exception ex2)
  29.         {
  30.             logger.ErrorException("Cannot recycle AppPool modifying web.config", ex2);
  31.         }
  32.     }
  33.     return rtn;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment