问题描述
我将文件路径存储为〜/FolderName/FileName,当我尝试以这种方式使用System.IO.FileInfo(filePath)打开文件时.它无法解密文件路径.此外,我在类DownloadFile中使用此语句,因此无法使用Page.Server.MapPath.有没有解决此问题的方法.
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();
}
其中文件路径的格式为〜/ComponentFolderForDownloading/FileName.exe
where the filepath is of the format ~/ComponentFolderForDownloading/FileName.exe
我该如何解决这个问题?
How can i solve this problem?
推荐答案
如果不能使用 Server.MapPath
确定文件位置,则需要使用其他方法. FileInfo
类不能在其构造函数中采用ASP.NET虚拟路径.它需要文件的真实物理路径.
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.
您需要从路径的开头剥离〜/
;也许将/
交换为 \
,然后将 Path.Combine
与应用程序的根目录一起使用以查找物理位置.但这假设您的位置在物理目录中,而不是虚拟目录中.
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
是专门为此目的而设计的.
Server.MapPath
was, of course, made specifically to do this.
一种替代方法是将文件的实际物理位置存储在数据库中;对虚拟ASP.NET的补充或替代.
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.
这篇关于asp.net的System.file.io中的相对路径问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!