asp.net mvc中内容文件夹的路径

时间:2015-05-20 13:32:30

标签: c# asp.net-mvc

我试图在我的程序中读取.txt文件:

using (StreamReader sr = new StreamReader(VirtualPathUtility.ToAbsolute("~/Content/txt/FamilyNames.txt")))
                    {
                        String line = sr.ReadToEnd();
                        Debug.WriteLine(line);
                    }

然而,这给了我以下路径,这是不正确的:

  

C:\内容\ TXT \ FamilyNames.txt

当我搜索这个时,我想出了许多解决方案,如:

Server.MapPath();

但这似乎是过时的代码?因为它在我的Visual Studio中无法识别,所以无法导入它......

那么获取内容文件夹中文件路径的正确解决方案是什么?

2 个答案:

答案 0 :(得分:9)

Server.MapPath需要HTTPContext。请改用System.Web.Hosting.HostingEnvironment.MapPath

using (StreamReader sr = new StreamReader(HostingEnvironment.MapPath("~/Content/txt/FamilyNames.txt")))

答案 1 :(得分:1)

你试过了吗?

 StreamReader(VirtualPathUtility.ToAppRelative("~/Content/txt/FamilyNames.txt")))
相关问题