Problem with relative path in System.file.io of asp.net

这一生的挚爱 提交于 2019-12-13 05:39:49

问题


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?


回答1:


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.




回答2:


If you know you are running in IIS, you can use:

HttpContext.Current.Server.MapPath("~/someurl");


来源:https://stackoverflow.com/questions/5859991/problem-with-relative-path-in-system-file-io-of-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!