62

How can i use the server.mappath method in a C# class library class ,which acts as my BusinessLayer for My ASP.NET WEbsite

Shyju
  • 214,206
  • 104
  • 411
  • 497

7 Answers7

122

By calling it?

var path = System.Web.HttpContext.Current.Server.MapPath("default.aspx");

Make sure you add a reference to the System.Web assembly.

Aaron Powell
  • 24,927
  • 18
  • 98
  • 150
  • 1
    i should say that system.web assembly does not exist in .net framework 4 – Arash Sep 30 '12 at 08:04
  • 16
    The worst solution! What if we need to use Business Layer classes out of HTTP Context? – Sergey Metlov Oct 29 '12 at 20:11
  • 6
    Here is the right answer http://stackoverflow.com/questions/12294458/asp-net-mvc-4-use-server-mappath-in-business-layer – Sergey Metlov Oct 29 '12 at 20:13
  • 1
    This answer is both not portable (outside of web applications) and not testable in unit tests. I agree with Ninja here. You can use IOC to inject the value, perhaps with an interface. – Trevor de Koekkoek Nov 17 '12 at 22:50
25

You can get the base path by using the following code and append your needed path with that.

string  path = System.AppDomain.CurrentDomain.BaseDirectory;
7

You should reference System.Web and call:

  HttpContext.Current.Server.MapPath(...)
Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
7

Use this System.Web.Hosting.HostingEnvironment.MapPath().

HostingEnvironment.MapPath("~/file")

Wonder why nobody mentioned it here.

James Skemp
  • 8,018
  • 9
  • 64
  • 107
Mahmood Dehghan
  • 7,761
  • 5
  • 54
  • 71
  • What's the difference between this and System.Web.HttpContext.Current.Server.MapPath ? I couldn't find any thing concrete between the two – Raj Kumar Feb 19 '20 at 08:43
4

Maybe you could abstract this as a dependency and create an IVirtualPathResolver. This way your service classes wouldn't be bound to System.Web and you could create another implementation if you wanted to reuse your logic in a different UI technology.

Tom Miller
  • 435
  • 8
  • 18
2
HostingEnvironment.MapPath
System.Web.Hosting.HostingEnvironment.MapPath(path);
Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93
Sachin Panchal
  • 159
  • 3
  • 9
2

Architecturally, System.web should not be referred in Business Logic Layer (BLL). Employ BLL into the solution structure to follow the separate of concern principle so refer System.Web is a bad practice. BLL should not load/run in Asp.net context. Because of the reason you should consider using of System.AppDomain.CurrentDomain.BaseDirectory instead of System.Web.HttpContext.Current.Server.MapPath

CodeSi
  • 401
  • 4
  • 6