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

cll*_*pse 23 c# io web-applications

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

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

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

Kla*_*sen 46

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

String template = File.ReadAllText(Server.MapPath("~/Templates/") + filename);
Run Code Online (Sandbox Code Playgroud)

  • @YatendraGoel System.Web.HttpContext.Current.Server.MapPath(字符串路径) (9认同)
  • 你能告诉我`Server`类所在的包. (2认同)

Meh*_*hin 7

您也可以使用此代码段.

using System.IO;
using System.Web.Hosting;
Run Code Online (Sandbox Code Playgroud)
using (StreamReader sr = new StreamReader(VirtualPathProvider.OpenFile("~/foo.txt")))
{
    string content = sr.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)