In my app I modify an image based on the users selected options. Each time I modify the default image I save and name it as user’s ID & date.now.tostring("yyyyMMddHHmmssf") to fix my problem with browser caching. This works fine, but now I could potentially end up with a lot of old images hanging around.
Now how can I delete all the images from my ~/Images/Temp/userID folder on the server? I was thinking about using the Session_End or Application_end subs in Global.asax, but I don’t think I can access any of my variables to get the path for the temp images.
How can I delete these temp files after session end or something similar?
Session End only fires for in-process sessions and it’s not guaranteed (e.g. the server could lose power and it wouldn’t fire). Application End shouldn’t be firing that often and (as you pointed out) you probably wouldn’t have the data you needed to perform the cleanup.
It’s not bad to perform cleanup work when a session ends, but for this particular problem there may be a better, more deterministic solution.
If unique naming is the source of the problem, several options come to mind:
Use a naming convention which allows you to run a Windows task periodically to identify old images and clean them up. Powershell is pretty flexible for tasks like this.
Serve the images with a varying query string parameter at the end of the name to avoid caching (but keep the file name consistent).
Example:
<img src="images/tim-medora.jpg?v=123" alt="picture" />Serve the images dynamically through a handler. This lets you control cache settings, vary the query string, etc.
Give the images a custom extension and set different cache settings for that extension in IIS. A web browser will have no problem with an image tag that points to a custom extension as long as its a valid image.