Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use and scope of global.asax (for file cleanup after application ends)

Tags:

On the subject of dynamically storing temporary images and handling their cleanup on a web server's file system: (using C# in .NET 3.5).

It was suggested that I use a global.asax file to handle this.

I just can't figure out how this thing works.

I have two separate applications...

I have figured out that the global.asax is supposed to be in the root directory of the website.

Questions:

1) How to I get the global.asax to fire for only these two specific applications.

2) both applications need to create a list of strings (the file locations) then delete them on the application termination. Do I instantiate this array in the app, or in the global.asax?

My code will look like this:

List<string> fileLocations = new List<string>();  
//I don't know where to put this.

//The next line of code will be in both applications (this could 
//be called many times in one application session.  The names of 
//the files are generated from the clock (milliseconds and 
//seconds combined, I might change this to use the actual 
//random class combined with sessionID)
fileLocations.Add(file);

void Application_End(object sender, EventArgs e) 
{
    //  Code that runs on application shutdown
    foreach(string file in fileLocations)
    {
        if(File.Exists(file))
            File.Delete(file);
    }    
}

I am confused about how the global.asax actually works. Is it used like an interface?

like image 672
Dave Avatar asked Aug 06 '09 18:08

Dave


1 Answers

A good place to look at how to use Global.asax is to read the ASP.NET Quickstart on it's usage. You have one per web application / site. It's kind of like Global level events.

Be aware, the Application_End event will not fire often, on most servers. It will only fire if the IIS app pool is unloaded/recyclyed, web.config modified , assemblies changed in /Bin,or someother situation where the webserver stops. On a popular site it could be weeks, months before your event ever fires.

like image 94
Dan Diplo Avatar answered Oct 11 '22 17:10

Dan Diplo