I have this line in some code I want to copy into my controller, but the compiler complains that
The name \'Server\' does not exist in the current con
The accepted answer's suggestion is good enough in most scenarios, however - since it depends on Dependency Injection - is limited to Controllers and Views: in order to have a proper Server.MapPath replacement that can be accessed from non-singleton helper classes we can add the following line(s) of code at the end of the Configure() method of the app's Startup.cs file:
// setup app's root folders
AppDomain.CurrentDomain.SetData("ContentRootPath", env.ContentRootPath);
AppDomain.CurrentDomain.SetData("WebRootPath", env.WebRootPath);
This way we'll be able to retrieve them from within any class (including, yet not limiting to, Controllers and Views) in the following way:
var contentRootPath = (string)AppDomain.CurrentDomain.GetData("ContentRootPath");
var webRootPath = string)AppDomain.CurrentDomain.GetData("WebRootPath");
This can be further exploited to create a static helper method that will allow us to have the same functionality as the good old Server.MapPath:
public static class MyServer
{
public static string MapPath(string path)
{
return Path.Combine(
(string)AppDomain.CurrentDomain.GetData("ContentRootPath"),
path);
}
}
Which can be used it in the following way:
var docPath = MyServer.MapPath("App_Data/docs");
For additional info regarding this approach and a bit of background, take a look at this post on my blog.