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

问题描述:

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

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

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

使用Server.MapPath("/path/to/file")和合格的结果File.ReadAllText()

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

埃。 'Server.MapPath()'做了诀窍。谢谢克劳斯:) – roosteronacid 2009-12-02 12:53:25

+0

你是最欢迎的:-) – 2009-12-02 13:13:33

+0

可以请你告诉我'服务器'类所在的包。 – 2010-03-07 09:17:23

您可以使用此代码段为好。

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

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