Refinance now before rates go up! Get multiple rate quotes at GetMyLender.com.

How to Maintain Session in ASP.NET application after deletion of subdirectory

In ASP.Net web application, When you delete a directory the session gets expired automatically. This is one of the frustrating error. It is the default nature if you are deleting a subdirectory within your application, your app domain will restart. This removes all session data.

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.
ASP.NET runs a File Monitor (FCN) that observes any change to the structure of the Virtual Directory. In case of any change the application is recycled.

One of the solution on this is 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

How to overcome this issue?


-You have to add following function in your code and then have to call it before you delete directory.
or
-You can call following function from Application_Start() method of the global.asax file.

Do not forget to import System.Reflection Namespace.

CSharp (C#)


    private void MaintainSessionWhileDeletingFolders()
{
       PropertyInfo p = typeof(HttpRuntime).GetProperty("FileChangesMonitor", BindingFlags.Public | BindingFlags.NonPublic | 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[]);
}

VB


Private Sub MaintainSessionWhileDeletingFolders()
        Dim p As PropertyInfo = GetType(HttpRuntime).GetProperty("FileChangesMonitor", BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Static)
        Dim o As Object = p.GetValue(Nothing, Nothing)
        Dim f As FieldInfo = o.GetType.GetField("_dirMonSubdirs", BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.IgnoreCase)
        Dim monitor As Object = f.GetValue(o)
        Dim m As MethodInfo = monitor.GetType.GetMethod("StopMonitoring", BindingFlags.Instance Or BindingFlags.NonPublic)
        m.Invoke(monitor, New Object() {})
    End Sub


Conclusion :

I hope that this article would have helped you to Maintain Session in ASP.NET application after deletion of directory. Your feedback and constructive contributions are always welcome.


No comments:

Post a Comment