I'm trying to implement what I'd call a "one time cache" for specific files in my ASP.NET 3.5 site. Upon request, the file is downloaded from a remote file server onto the web server, then served up by my page. The problem arises when I go to delete it. If I delete the file in the OnUnload
method, the client doesn't have time to retrieve it. Is there some way of detecting the download of a file and deleting it immediately after it is first accessed? My code is like this:
private bool _deleteFlag = false;
private string _deleteFile = string.Empty;
protected void Page_Load(object sender, EventArgs e) {
if (!string.IsNullOrEmpty(Request.QueryString["file"])) {
_deleteFlag = Request.QueryString["file"].Contains(@"cache/");
_deleteFile = Request.QueryString["file"];
}
}
protected override void OnUnload(EventArgs e) {
if (_deleteFlag) {
// Can't delete here; the client is still trying to retrieve it.
System.IO.File.Delete(Server.MapPath(_deleteFile));
}
base.OnUnload(e);
}
I'm leaning towards writing an IHttpHandler
that overrides the file request, but that feels like overkill.