Reputation: 7601
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?
Upvotes: 0
Views: 4591
Reputation: 25692
If you know you are running in IIS, you can use:
HttpContext.Current.Server.MapPath("~/someurl");
Upvotes: 1
Reputation: 40160
If you can't use Server.MapPath
for determining the file location, you need to use something else. The FileInfo
class 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 use Path.Combine
with 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.MapPath
was, 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.
Upvotes: 1