Tutorial :How do i force a file to be deleted? Windows server 2008


On my site a user may upload a file (pic, zip, audio, video, whatever). He then may decide to replace it with a newer revision. This user may upload a file, make a post then decide to put up a new revision replacing the old (lets say its a large zip or tar.gz file). Theres a good chance people may be downloading it if he sent out an email or even im for the home user.

Problem. I need to replace the file and people may be downloading and it may be some minutes before it is deleted. I dont want my code to stall until i cant delete or check every second to see if its unused (especially bad if another user can start and he takes long creating a cycle).

How do i delete the file while users are downloading the file? i dont care if they stop i just care that the file can be replaced and new downloads are the new revision.


lajuette's answer is right, the easiest solution is to work around the file locking altogether:

  1. When a user uploads file foo.zip, internally store it as foo-v1.zip.
  2. Create a mapping file somewhere (database, code, whatever) that maps foo.zip to foo-v1.zip.
  3. Rather than exposing a direct link to the file, expose a link to a service that gets the file: mysite.com/Download?foo.zip or something. This service uses the mapping to determine which version of the file to send to the client.
  4. When a new version is uploaded, create foo-v2.zip and update the mapping file.

It wouldn't be that hard to write a scheduled task that cleans up old, un-mapped files.


What about referencing the files indirectly?

A mapping script, maps a virtual file entry from your site to a real file . If the user wants to upload a new revision of his file you just update the mapping, not the real file.

You can install a daily task that scans all files and deletes all files without a mapping and without open connections.


If your oppose to a database and If the filenames are in a fix format (such as user/id.ext) you could append the id with a revision number and enumerate the folder using a pattern (user/id-*) and use the latest revision.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »