Search code examples
c#asp.netcontextpath

Do we always need to use context.Server.MapPath? what if I cache the result?


I find it weird to use context.Server.MapPath every time just to determine physical location of some known directory/file under app_data folder. I have an understanding that once an application is running, it must not be possible to have its physical location be changed without first shutting it down. If this is true, then I can cache physical path of app_data on application_start and use the cache value for its execution lifetime!

I need experts opinion on this matter. Is my assumption right? there's no possibility of changing the physical path of an application without restarting it, right?

If this is true, It will save me tons of time from having to include context as a parameter in every odd method!

Clarity of the method interface is most important to me, and <context> just doesn't fit into that.

BTW, I'm using shared hosting so I have no control on application physical placement. Does this matter?


Solution

  • The path is relative to the current request, so MapPath("foo") might have a different result on requests at different urls. However, if your path is relative to the app-root ("~/foo") or relative to the site-root ("/foo") you can pretty much cache to your heart's content.

    There is perhaps an edge-case scenario of people adding virtual directories inside IIS during execution, but that is vanishingly unlikely, and is pretty-much going to cause pain anyway.