Enabling secure file download in Asp .Net 2.0

I was trying my hands on Asp .net after a long time, and then came across an interesting problem. I was trying to write a function to make a secure download of web based files, that is I was trying to hide the path of file from user, who is going to download a file from my site. Igoogled a lot, but could not find the exact thing, that I was looking for. Then I collected the pieces of codes from my search, and created that function out of it. This function can be called from any event and will initiate the download without letting users know the path of target file.
The code goes here:
public void download(string fileName, string parentDirectory)
{
string path = Server.MapPath(pare);
FileInfo f1 = new FileInfo(path + “/” + fileName);
        if (f1.Exists)
        {
            Response.Clear();
            Response.AddHeader(“Content-Disposition”, “attachment; filename=” + f1.Name);
            Response.AddHeader(“Content-Length”, f1.Length.ToString());
            Response.ContentType = “application/octet-stream”;
            Response.WriteFile(f1.FullName);
            Response.End();
        }
        else
            Response.Write(path + “/” + fileName);
}
Note: To use this code, one must use the System.IO namespace.


Leave a Reply

Your email address will not be published. Required fields are marked *