使用Web应用程序中的相对路径读取文件的内容
如何使用相对路径/ URL读取Web应用程序中文本文件的内容?
这些文件位于我的应用程序根目录中。
我不想指定我想要访问的文件的完整路径,因为我的测试环境不是我的生产环境的精确镜像。
使用Server.MapPath("/path/to/file")
并将结果传递给File.ReadAllText()
:
String template = File.ReadAllText(Server.MapPath("~/Templates/") + filename);
您也可以使用此代码段。
using System.IO; using System.Web.Hosting;
using (StreamReader sr = new StreamReader(VirtualPathProvider.OpenFile("~/foo.txt"))) { string content = sr.ReadToEnd(); }