使用Web应用程序中的相对路径读取文件的内容

时间:2009-12-02 12:44:01

标签: c# web-applications io

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

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

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

2 个答案:

答案 0 :(得分:46)

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

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

答案 1 :(得分:7)

您也可以使用此代码段。

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

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