Wednesday 30 June, 2010

Disable Session Expiration when using Directory.Delete()

As you may already know, one of the reasons why the asp.net worker process recycles which kills all the session variables in memory is due to dynamically deleting a folder under the root application folder. You have two options to follow in this case

1- To use out-of-process mode session
2- To use the below code which uses reflection to disable monitoring for the folders inside the application. In this way, once you delete a folder, the Application domain won't restart thus you won't be losing any session variable

PropertyInfo p = typeof(System.Web.HttpRuntime).GetProperty("FileChangesMonitor", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
object o = p.GetValue(null, null);
FieldInfo f = o.GetType().GetField("_dirMonSubdirs", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
object monitor = f.GetValue(o);
MethodInfo m = monitor.GetType().GetMethod("StopMonitoring", BindingFlags.Instance | BindingFlags.NonPublic);
m.Invoke(monitor, new object[] { });

Do not forget to import System.Reflection Namespace

Hope this helps,

No comments:

Post a Comment