【问题标题】:Read contents of a file using a relative path in a Web Application使用 Web 应用程序中的相对路径读取文件的内容
【发布时间】:2010-12-22 09:44:46
【问题描述】:

如何使用相对路径/URL 在我的 Web 应用程序中读取文本文件的内容?

这些文件位于我的应用程序根目录中。

我不想指定要访问的文件的完整路径,因为我的测试环境不是我的生产环境的精确镜像。

【问题讨论】:

    标签: c# web-applications io


    【解决方案1】:

    使用Server.MapPath("/path/to/file") 并将结果传递给File.ReadAllText()

    String template = File.ReadAllText(Server.MapPath("~/Templates/") + filename);
    

    【讨论】:

    • 你能告诉我Server类位于哪个包中吗?
    • @YatendraGoel System.Web.HttpContext.Current.Server.MapPath(字符串路径)
    【解决方案2】:

    您也可以使用此代码 sn-p。

    using System.IO;
    using System.Web.Hosting;
    

    using (StreamReader sr = new StreamReader(VirtualPathProvider.OpenFile("~/foo.txt")))
    {
        string content = sr.ReadToEnd();
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-02
      • 2011-01-24
      • 2013-10-25
      • 1970-01-01
      • 2013-06-28
      • 2011-06-30
      • 1970-01-01
      • 2012-07-02
      • 1970-01-01
      相关资源
      最近更新 更多