【问题标题】:Get full path to file while debugging using IIS Express使用 IIS Express 进行调试时获取文件的完整路径
【发布时间】:2012-10-29 00:23:54
【问题描述】:

我有一个正在尝试调试的 .NET 应用程序,并且我的部分应用程序从我的项目中加载了一个文件。该文件位于

C:\Users\USER_FOLDER\Documents\Visual Studio 2012\Projects\MY_PROJECT\_templates\myFile.html

在我的代码中,我指定了文件的相对路径并使用 DirectoryInfo 类来获取我的文件的完整目录路径:

string myFile = (new DirectoryInfo("_templates/myFile.html")).FullName;

但是,这会返回以下路径(额外的 \'s 作为转义字符):

"C:\\Program Files\\IIS Express\\_templates\\myFile.html"

我希望在 IIS Express 中调试时返回的路径与我列出的第一个路径匹配,而不是第三个。为什么是这样?我还需要在我的项目中设置其他东西以使其正确导出路径吗?我假设如果我将代码部署到 IIS7 站点就不会发生这种情况,但我还没有达到那个测试级别。

【问题讨论】:

  • 如果它返回的Program Files\\IIS Express\` it means your launching it from that directory path so be more specific about the directory path. Considering "_templates/myFile.html" 将是父目录中的本地目录,则它不是很具体。
  • 在该注释中,调用 Server.MapPath 会返回正确的路径,而无需更具描述性。进入这个我认为我不必更具描述性,因为与其他语言一样,我将路径视为相对于引用文件的脚本的位置,但为了读取其内容。 NET 服务器需要一个完全限定的路径 URI,而我只是使用了错误的对象来派生它。为什么我的有效问题被否决令人困惑。

标签: c# .net iis iis-express directoryinfo


【解决方案1】:

使用Server.MapPath:

Server.MapPath("~/_templates/myFile.html")

HttpServerUtility.MapPath:

HttpServerUtility.MapPath("~/_templates/myFile.html")

【讨论】:

  • 谢谢! Server.MapPath 为我工作,但我无法让 HttpServerUtility.MapPath 工作。对于 HttpServerUtility,它一直抱怨 An object reference is required for the non-static field, method, or property 'System.Web.HttpServerUtility.MapPath(string)' 我尝试了各种编写它的方法,但没有任何效果,所以我将只使用 Server.MapPath。再次感谢。
  • 不确定这是否是完全相同的情况,但我遇到了相同的对象引用问题。我使用 HttpContext 解决了它。如 - HttpContext.Current.Server.MapPath();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-10
  • 2019-02-09
  • 2012-04-19
  • 1970-01-01
相关资源
最近更新 更多