user4080876
user4080876

Reputation:

Path to content folder in asp.net mvc

I'm 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 following path, which is incorrect:

C:\Content\txt\FamilyNames.txt

When I search for this I come up with numerous solutions like:

Server.MapPath();

But this seems to be outdated code? Because it doesn't get recognized in my Visual Studio, can't import it...

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

Upvotes: 7

Views: 17461

Answers (2)

LocEngineer
LocEngineer

Reputation: 2917

Server.MapPath needs a HTTPContext. Use System.Web.Hosting.HostingEnvironment.MapPath instead.

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

Upvotes: 17

Antoine Pelletier
Antoine Pelletier

Reputation: 3316

Have you tried :

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

Upvotes: 1

Related Questions