【问题标题】:Problem with relative path in System.file.io of asp.netasp.net 的 System.file.io 中的相对路径问题
【发布时间】:2011-05-02 16:58:34
【问题描述】:

我将数据库中的文件路径存储为 ~/FolderName/FileName 并且当我尝试以这种方式使用 System.IO.FileInfo(filePath) 打开文件时。它无法破译文件路径。此外,我在类 DownloadFile 中使用此语句,因此我无法使用 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

我该如何解决这个问题?

【问题讨论】:

  • 有什么理由不能在 downloadFile 类中使用 MapPath?
  • @Joe 有人可以向我解释一下 Server.MapPath("~/ComponentFolder/File1.exe") 和 Server.MapPath("~\ComponentFolder\File1.exe") 有什么区别用这个 / 和 \ ??

标签: c# asp.net relative-path


【解决方案1】:

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

您需要从路径的前面去掉~/;也许将/ 换成\,然后使用Path.Combine 和应用程序的根目录来查找物理位置。但这假设您的位置位于物理目录中,而不是虚拟目录中。

Server.MapPath 当然是专门为此设计的。

另一种方法是将文件的真实物理位置存储在数据库中;除了虚拟的 ASP.NET 之外,也可以代替虚拟的 ASP.NET。

【讨论】:

  • 有人可以向我解释一下 Server.MapPath("~/ComponentFolder/File1.exe") 和 Server.MapPath("~\ComponentFolder\File1.exe") 有什么区别吗/ 和 \ ??
【解决方案2】:

如果你知道你在 IIS 中运行,你可以使用:

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

【讨论】:

  • 有人可以向我解释一下 Server.MapPath("~/ComponentFolder/File1.exe") 和 Server.MapPath("~\ComponentFolder\File1.exe") 有什么区别吗/ 和 \ ??
  • 反斜杠是 Windows 文件系统约定。我总是对 Internet URL 使用正斜杠。
猜你喜欢
  • 2016-03-05
  • 2019-07-18
  • 2014-07-03
  • 1970-01-01
  • 2011-07-09
  • 2014-05-09
  • 2016-01-08
  • 2011-04-29
  • 1970-01-01
相关资源
最近更新 更多