ASP.NET MVC4

How to use Server.MapPath in ASP.NET MVC 4?

Sunny Sharma1 min read
You can use Server.MapPath in ASP.NET MVC 4 like this:

String path = HttpContext.Current.Server.MapPath(“~/myFolder/myFile.txt”);

You can use the way mentioned above but ASP.NET MVC 4 has another way to map files on server  and that is using HostingEnvironment class. Actually Server.MapPath() also internally calls HostingEnvironment.MapPath() to map the file paths on server. It belongs to the  System.Web.Hosting namespace. SO you can use it like this:

using System.Web.Hosting;
String path = HostingEnvironment.MapPath(“~/myFolder/myFile.txt”);

It is more recommended because its static and not dependent on current context unless you want it to use.

Thanks!


Sunny Sharma

Security and engineering leader. Notes from running AI, Azure and security in production.

2 thoughts on “How to use Server.MapPath in ASP.NET MVC 4?”

Leave a Comment