I’m storing the file path in the database as ~/FolderName/FileName and when i try to open the file using System.IO.FileInfo(filePath) in this manner. It is not able to decipher the file path. Moreover i’m using this statement in a class DownloadFile, so i’m not able to use Page.Server.MapPath. Is there a work around for this problem.
These are the following lines of code that i’m using:
if (dr1.Read())
{
String filePath = dr1[0].ToString();
HttpContext.Current.Response.ContentType = "APPLICATION/OCTET-STREAM";
String disHeader = "Attachment; Filename=\"" + fileName + "\"";
HttpContext.Current.Response.AppendHeader("Content-Disposition", disHeader);
System.IO.FileInfo fileToDownload = new System.IO.FileInfo(filePath);
string fullName = fileToDownload.FullName;
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.WriteFile(fileToDownload.FullName);
sqlCon.Close();
}
where the filepath is of the format ~/ComponentFolderForDownloading/FileName.exe
How can i solve this problem?
If you can’t use
Server.MapPathfor determining the file location, you need to use something else. TheFileInfoclass can not take an ASP.NET virtual path in its constructor. It needs the real, physical path of the file.You’ll need to strip the
~/from the front of the path; perhaps exchange the/for a\, and then usePath.Combinewith the root directory of your application to find the physical location. But that assumes that your locations are in physical directories – not virtual ones.Server.MapPathwas, of course, made specifically to do this.An alternative would be to store the real, physical locations of the files in the DB; either in addition to or in stead of the virtual, ASP.NET ones.