How can i use the server.mappath method in a C# class library class ,which acts as my BusinessLayer for My ASP.NET WEbsite
7 Answers
By calling it?
var path = System.Web.HttpContext.Current.Server.MapPath("default.aspx");
Make sure you add a reference to the System.Web assembly.

- 24,927
- 18
- 98
- 150
-
1i should say that system.web assembly does not exist in .net framework 4 – Arash Sep 30 '12 at 08:04
-
16The worst solution! What if we need to use Business Layer classes out of HTTP Context? – Sergey Metlov Oct 29 '12 at 20:11
-
6Here 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
-
1This 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
You can get the base path by using the following code and append your needed path with that.
string path = System.AppDomain.CurrentDomain.BaseDirectory;

- 1,214
- 1
- 17
- 31
You should reference System.Web and call:
HttpContext.Current.Server.MapPath(...)

- 168,566
- 31
- 210
- 223
Use this System.Web.Hosting.HostingEnvironment.MapPath().
HostingEnvironment.MapPath("~/file")
Wonder why nobody mentioned it here.

- 8,018
- 9
- 64
- 107

- 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
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.

- 435
- 8
- 18
HostingEnvironment.MapPath
System.Web.Hosting.HostingEnvironment.MapPath(path);

- 8,329
- 6
- 58
- 93

- 159
- 3
- 9
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

- 401
- 4
- 6