Server.Mappath in C# classlibrary
Asked Answered
J

7

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

Jacktar answered 29/7, 2009 at 11:11 Comment(0)
L
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.

Lutyens answered 29/7, 2009 at 11:14 Comment(4)
i should say that system.web assembly does not exist in .net framework 4Kentigera
The worst solution! What if we need to use Business Layer classes out of HTTP Context?Pepe
Here is the right answer #12294958Pepe
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.Charinile
D
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;
Dexter answered 4/12, 2013 at 5:25 Comment(0)
N
7

You should reference System.Web and call:

  HttpContext.Current.Server.MapPath(...)
Nankeen answered 29/7, 2009 at 11:14 Comment(0)
T
7

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

HostingEnvironment.MapPath("~/file")

Wonder why nobody mentioned it here.

Tenuis answered 5/1, 2016 at 12:19 Comment(1)
What's the difference between this and System.Web.HttpContext.Current.Server.MapPath ? I couldn't find any thing concrete between the twoKilmer
N
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.

Nephograph answered 8/4, 2012 at 16:24 Comment(0)
L
2
HostingEnvironment.MapPath
System.Web.Hosting.HostingEnvironment.MapPath(path);
Lyophilize answered 26/7, 2016 at 11:16 Comment(0)
A
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

Aeneid answered 6/9, 2017 at 6:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.