0

Newbie question...

If I have a file that is in the root of the web app. How do I programmaticaly query the path of that file? ie, what directory it is in?

4 Answers 4

2
System.Web.HttpServerUtility.MapPath( "~/filename.ext" );

will give you the physical (disk) path, which you would use with System.IO methods and such.

System.Web.Hosting.VirtualPathUtility.ToAbsolute( "~/filename.ext" );

will give you the "absolute" virtual path. This won't be the full url, but isn't necessarily the root of the domain, either. It could be something like

/admin/filename.ext

if the application is rooted in a subdirectory.

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

Comments

0

was close to what I was wanting..... except that didn't seem to compile or wasn't valid in the context I was calling it.

However I found what I needed with System.Web.HttpRuntime.AppDomainAppPath

3 Comments

Ah. That should be equivalent to HttpServerUtility.MapPath( "~" )
If I use that, I get... Error 1 An object reference is required for the non-static field, method, or property 'System.Web.HttpServerUtility.MapPath(string)'
That's odd. Where are you calling it from?
0

If you are in your ASPX markup you can break out to C# and use the ResolveUrl method like so:

<%= Page.ResolveUrl("~/PathFromRoot/YourFile.pdf") %>

Comments

0

Old question, I know, but I found it while searching for a similar answer. Unless the API has changed, the reason why harpo's answer isn't working is because MapPath is an instance method, not a static method. But fear not--there's an instance of HttpServerUtility present in each instance of Controller--the Server property. So in your case, if you're within a controller (or, I suspect, a view):

var appRoot = Server.MapPath("~/");

That should do the trick!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.