Search This Blog

Thursday, October 8, 2015

A bit about Virtual Paths in ASP.NET applications

In referring to resources such as images in your asp.net application, it is useful to know that a tilde (~) represents the root directory of the application (which you can double-check by taking a look at the framework variable HttpRuntime.AppDomainAppVirtualPath). Using it to reference resource is better since this way is not dependent of location of where the reference is being made.

 For instance, if you are referencing myImage.jpg, which resides in /Content/Images, in a view located at /Views/Partials, if you were to reference the image by its physical path you would need to manually go down to the root folder and then climb up to Content/Images. And if you copy + paste the <img src="..." />  tag where this reference was coded to another view, you might end up with a broken link, since suffices that the source file making the reference be in a different position in the hierarchy for the link to be broken.

You can get over this by having your image tag like <img src="~/Content/Images/myImage.jpg" />. .NET will always translate this path to [contents of HttpRuntime.AppDomainAppVirtualPath]/Content/Images/myImage.jpg. Using the static class VirtualPathUtility, which I just learned about, may also come in handy.

Click here for a good resource on the subject.