Content folder path in asp.net mvc

I am trying to read a .txt file in my program:

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

      

This, however, gives me the following path, which is incorrect:

C: \ Content \ TXT \ FamilyNames.txt

When I search for this, I come up with many solutions such as:

Server.MapPath();

      

But does this seem to be legacy code? Since it is not recognized in my Visual Studio, it cannot be imported ...

So what is the correct solution to get the file path in the content folder?

+3


source to share


2 answers


The .MapPath server needs an HTTPContext. Use instead System.Web.Hosting.HostingEnvironment.MapPath

.



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

      

+5


source


You tried:



 StreamReader(VirtualPathUtility.ToAppRelative("~/Content/txt/FamilyNames.txt")))

      

+1


source







All Articles