12

I have some processes that run without an HttpContext in an ASP.NET MVC web application. This process needs to be able to determine the physical path to the Contents directory of the application for reading/writing data. But, since it is without an HttpContext, I don't get to use fancy things like Server.MapPath and such. Suggestions?

2
  • 1
    Even if HttpContext.Current can be null, Server.MapPath will still work. If you don't "have" it, perhaps you mean that you miss the reference to System.Web? Commented Aug 23, 2010 at 16:50
  • @Abel: You will not "have" a reference to "Server" to use .MapPath in, for example, a static constructor, because "Server" is a property of HttpContext.Current (and also a property of HttpApplication), neither of which will be reliably available in such a static context. "Server" is of type "HttpServerUtility" whose constructor is internal, so you can't use it unless you can get it from either HttpContext.Current or HttpApplication in Global.asax. Therefore, HttpRuntime.AppDomainAppPath is what should be used, as you posted in your answer below. Commented Aug 1, 2013 at 0:54

2 Answers 2

15

In a website, it is best to use HttpRuntime.AppDomainAppPath, because in certain moments of the execution path (i.e. when the site starts up), there's no HttpContext.Current available.

See also this post.

Sign up to request clarification or add additional context in comments.

4 Comments

Why is HttpRuntime.AppDomainPath better than AppDomain.BaseDirectory?`
Because of its semantics. When you are inside the HttpRuntime, it is better to ask the runtime the correct path, instead of poking around yourself. Also, it makes your code more readable and your intends clearer. Finally, implementations may change, but even in that case, HttpRuntime will still return the correct path and AppDomain will not (same may apply to the rare case where you have started a separated AppDomain).
Thanks. I edited above because it is actually AppDomainAppPath not AppDomainPath (at least on .NET4)
@Matt: thanks for the edit, you are right about the typo (and it's in all versions of .NET ;-)
4

The best way to do this is using the AppDomain.BaseDirectory property. As long as you don't fiddle with custom application domains, it will point to your root application directory. In other words; these two string would be the same:

string mapUsingAppDomain = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Contents"); string mapUsingServer = HttpContext.Current.Server.MapPath("~/Contents"); 

1 Comment

In a website, it is preferred to use HttpRuntime.AppDomainPath, which is guaranteed to return the correct path. But driis is right, I can think of very few cases where these methods may return something different.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.