Use Server.MapPath in Business Layer
Asked Answered
C

4

8

My business layer creates files and needs to save them in the App_Data folder of my asp.net mvc 4 web frontend.

I could use Server.MapPath in the business layer to get the physical path of the App_Data folder. But i want to avoid a reference to System.Web in the business layer.

Are there other ways to get the path to App_Data in business layer?

Coatee answered 6/9, 2012 at 6:51 Comment(0)
H
32

The correct way to deal with this is to have the presentation layer pass the path into the business layer.

To put this another way, the purpose of having a business layer is to create a separation of concerns between the ui and business processes. If you force the business process to know about the ui layer, then you are violating that separation of concerns.

There are a number of ways you could deal with this. You could pass the path into the business layer when the business layer is constructed, such as via constructor initialization or through dependency injection. Or you could pass it to the method call. Or you could create some form of configuration file that your business layer loads that contains the path.

There are lots of ways of going about this that do not violate separation of concerns.

Hebetate answered 6/9, 2012 at 7:11 Comment(0)
D
18

you can use

string  path = System.AppDomain.CurrentDomain.BaseDirectory+"App_Data";
Darcee answered 4/12, 2013 at 5:30 Comment(1)
I like this approach, actually. It doesn't create any dependency on ASP.NET, and is only using dependencies that common to any .NET application. The only concern is that it does tie things to the OS to some degree if you're not careful.Hebetate
M
5
string path = HostingEnvironment.MapPath("~\\App_Data");

It works for me

Mobcap answered 12/9, 2015 at 5:38 Comment(1)
HostingEnvironment is part of System.WebAdjudication
R
4

I know its an old question but still a very valid one. I have seen all answers here and I want to write notes of the best of all knowledge here.

  1. It is recommended NOT to use System.Web assembly as it conflicts S.O.L.I.D principles. For Example, If we use System.Web and try to use that DLL in a Windows Form / Console / WPF application then context will always remain null in that scenario.
  2. For example you can want to access data.txt file under the folder App_data folder. In DLL you should use following Code

    string rootDirectoryPath = AppDomain.CurrentDomain.BaseDirectory; string pathFinalAccessFile = Path.Combine(rootDirectoryPath, "App_Data", "data.txt");

Rather than appending path and file name manually with quotes and "\" you should use Path.Combine Method in C# (as shown in code above).

Rousing answered 4/7, 2018 at 6:3 Comment(2)
can anyone guide me why my answer received the downvote?Rousing
Most likely because you just repeated info in other posts, with the small exception of using the Path.Combine.Hebetate

© 2022 - 2024 — McMap. All rights reserved.