You can't, not reliably. There are events you can get when the user moves to a new page, but that doesn't mean that you will always gets them: what it the users browser crashes, the power fails, or one of several other reasons? Your file will get left behind, and probably never deleted.
Why are you extracting them from the database to files? The only reason I can think of is to make it easy for the user to download them - so why not let the user download the file directly from the database instead? That way, no temporary files are created, so there is nothing to clear up.
What I do is to set a link to an apsx page as the download link:
private static HtmlTableRow AddDownloadFile(Downloadable dl)
{
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell cell = new HtmlTableCell();
cell.InnerHtml = "<a href=\"FileTransferDownload.aspx?file=" + dl.Id + "\" target=\"_blank\">" + dl.FileName + "</a>";
row.Cells.Add(cell);
cell = new HtmlTableCell();
cell.InnerText = dl.Version.ToString();
row.Cells.Add(cell);
cell = new HtmlTableCell();
cell.InnerText = dl.UploadedOn.ToString();
row.Cells.Add(cell);
return row;
}
And then the page handles the work:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileTransferDownload.aspx.cs" Inherits="FileTransferDownload" %>
<%
string guid = Request.QueryString["file"];
string fileName = "ERROR";
byte[] data = new byte[] { 0, 0, 0, 0 };
string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DownloadDatabase"].ConnectionString;
using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon))
{
con.Open();
string strcmd = "SELECT [iD] ,cn.[fileName],[description] ,[dataContent] ,[version] " +
"FROM dlContent cn " +
"WHERE cn.iD=@ID";
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(strcmd, con))
{
cmd.Parameters.AddWithValue("@ID", guid);
using (System.Data.SqlClient.SqlDataReader r = cmd.ExecuteReader())
{
if (r.Read())
{
fileName = (string) r["filename"];
data = (byte[]) r["dataContent"];
}
}
}
}
Response.Clear();
Response.AddHeader("Cache-Control", "no-cache, must-revalidate, post-check=0, pre-check=0");
Response.AddHeader("Pragma", "no-cache");
Response.AddHeader("Content-Description", "File Download");
Response.AddHeader("Content-Type", "application/force-download");
Response.AddHeader("Content-Transfer-Encoding", "binary\n");
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.BinaryWrite(data);
Response.End();
%>