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="" />

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.

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: