C# asp.net的System.file.io中存在相对路径问题

C# asp.net的System.file.io中存在相对路径问题,c#,asp.net,relative-path,C#,Asp.net,Relative Path,我将文件路径存储在数据库中为~/FolderName/FileName,当我尝试以这种方式使用System.IO.FileInfo(filePath)打开文件时。它无法破译文件路径。此外,我正在类下载文件中使用此语句,因此无法使用Page.Server.MapPath。有解决这个问题的办法吗 以下是我正在使用的代码行: if (dr1.Read()) { String filePath = dr1[0].ToString(); HttpContext.Current.Respon

我将文件路径存储在数据库中为~/FolderName/FileName,当我尝试以这种方式使用System.IO.FileInfo(filePath)打开文件时。它无法破译文件路径。此外,我正在类下载文件中使用此语句,因此无法使用Page.Server.MapPath。有解决这个问题的办法吗

以下是我正在使用的代码行:

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


如何解决此问题?

如果无法使用
Server.MapPath
确定文件位置,则需要使用其他方法。
FileInfo
类不能在其构造函数中采用ASP.NET虚拟路径。它需要文件的真实物理路径

您需要从路径的前面剥离
~/
;也许可以将
/
交换为
\
,然后使用
路径。将
与应用程序的根目录组合以查找物理位置。但这假设您的位置在物理目录中,而不是虚拟目录中

当然,
Server.MapPath
就是专门为此而设计的


另一种方法是将文件的真实物理位置存储在数据库中;除了虚拟的ASP.NET之外,或者代替虚拟的ASP.NET。如果您知道自己正在IIS中运行,可以使用:

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

有什么原因不能在downloadFile类中使用MapPath吗?@Joe有人能解释一下Server.MapPath(“~/ComponentFolder/File1.exe”)和Server.MapPath(“~\ComponentFolder\File1.exe”)之间的区别吗?有人能解释一下Server.MapPath(“~/ComponentFolder/File1.exe”)和\?有人能解释一下Server.MapPath(“~/ComponentFolder/File1.exe”)之间的区别吗和Server.MapPath(“~\ComponentFolder\File1.exe”)以及此/和\?反斜杠是Windows文件系统约定。我总是对Internet URL使用前斜杠。有人能解释一下Server.MapPath(“~/ComponentFolder/File1.exe”)和Server.MapPath(“~\ComponentFolder\File1.exe”)与此/和\”之间的区别吗??