Thursday, March 24, 2011

How Can I Find The Path To A Folder from a Controller Constructor in ASP.NET MVC?

I am trying to get the path to a folder in my website root and save it to a class property when my controller constructor is called:

public TestController:Controller{
    string temp;

    public TestController(){
        temp = "";
        }

    }

I have tried the following:

temp = Server.MapPath("~/TheFolder/"); // Server is null - error.
temp = Request.PhysicalApplicationPath + @"TheFolder\"; // Request is null - error.

Any ideas?

From stackoverflow
  • AppDomain.CurrentDomain.BaseDirectory will give you the root of your site. So:

    temp = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TheFolder");
    

    (Update thanks to Marc Gravell's comment)

    Marc Gravell : Path.Combine would be nicer ;-p
  • Try going through the ControllerContext. Forgive my syntax, but it should something like this:

    base.[Controller?]Context.HttpContext.Server.MapPath();
    

    If Server is still null in that situation, are you running outside of a web request (ie. in a test)?

  • Do you actually need this path during the constructor? If you don't need it until the main page cycle begins, consider deferring it - just using a regular property; something like

    public string BasePath {
        get { return Server.MapPath("~/TheFolder/"); }
    }
    

    Then when this is used during the page cycle, it should be fine. You could cache it if you really want to, but I don't imagine this is going to be a bottleneck:

    private string basePath;
    public string BasePath {
        get {
            if(basePath == null) basePath = Server.MapPath("~/TheFolder/");
            return basePath;
        }
    }
    
    81bronco : That's a good idea. I might end up going this route later. Thanks!

0 comments:

Post a Comment