C# 在 Web 应用程序中使用相对路径读取文件的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1832682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read contents of a file using a relative path in a Web Application
提问by cllpse
How can I read the contents of a text file in my Web Application, using a relative path/URL?
如何使用相对路径/URL 在我的 Web 应用程序中读取文本文件的内容?
The files are located in a directory at the root of my application.
这些文件位于我的应用程序根目录中。
I don't want to specify the full path to the file I want to access, since my test environment is not an exact mirror of my production environment.
我不想指定我想要访问的文件的完整路径,因为我的测试环境不是我的生产环境的精确镜像。
采纳答案by Klaus Byskov Pedersen
Use Server.MapPath("/path/to/file")
and pass the result of that to File.ReadAllText()
:
使用Server.MapPath("/path/to/file")
并将结果传递给File.ReadAllText()
:
String template = File.ReadAllText(Server.MapPath("~/Templates/") + filename);
回答by Mehdi Golchin
You can use this code snippet as well.
您也可以使用此代码片段。
using System.IO;
using System.Web.Hosting;
using (StreamReader sr = new StreamReader(VirtualPathProvider.OpenFile("~/foo.txt")))
{
string content = sr.ReadToEnd();
}