ASP.NET Project Image Paths

I still see a lot of developers getting confused with the image paths in an ASP.NET application.

Here’s a very quick primer to help you with it:

Absolute Path

<img src="http://www.yourxyxwebsite.com/Images/SomeImage.jpg" />

Images folder in site root directory ("/")

<img src="/Images/SomeImage.jpg" />

Images folder in the current directory ("./")

<img src="./Images/SomeImage.jpg" />

./image.jpg and image.jpg are the same and refer to the current directory


Images folder in the parent directory ("../")

<img src="../Images/SomeImage.jpg" />

Root operator to identify root of the current application (~)

<asp:image runat="server" id="someImage"
  ImageUrl="~/Images/SomeImage.jpg" />

Using ResolveUrl()

We just saw that ~/ means the application physical root folder. However using this in the following format will not work on a webpage with a Master Page (ex: <img src="~/Images/SomeImage.jpg" />)

So instead use the Page.ResolveUrl() which translates an application relative URL to an absolute URL.

<img src='<%=Page.ResolveUrl(‘~/Images/SomeImage.jpg’) %>' />

Page.ResolveUrl converts the tilde ~ into the correct path for the current application directory.

I hope I have covered most of the frequently used paths. In case you have any doubts, just use the comments section to clarify them.




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: