ASP.NET: Reference files with relative paths
From Wiki
Summary: An example of how to reference files based on the root path of the application.
If you have a Master Page that references a style sheet, you have a couple of options on how to add the href attribute that references files such as javascript or css documents. Some of these options include:
1) Use an absolute path
You could hard code the full http path to this file so that it looks like:
- <link id="stMainLayout" rel="stylesheet" type="text/css" media="screen" href="http://aspnetlibrary.com/stylesheets/mainlayout.css" />
However, the problem with this is that it doesn't work on your development machine as the path will most likely point to your localhost.
2) Use a relative path
You can add a relative path so that the style sheet is referenced in relation to the current page e.g.
- <link id="stMainLayout" rel="stylesheet" type="text/css" media="screen" href="stylesheets/mainlayout.css" />
The problem with this method comes when you want to use the same Master Page for content pages that are placed in different folders within your application. As the path is relative to your content page and not the Master Page, pages which reside in a different directory will not be able to reference the correct path.
The Solution
One method I use is to make the link to the stylesheet into a server side accessible control by adding the runat="server" tag e.g.
- <link id="stMainLayout" rel="stylesheet" type="text/css" media="screen" runat="server" href="~/stylesheets/mainlayout.css"/>
By doing this, you can use the tilde sign (~) at the beginning of the href attribute which will return the root directory each time, regardless of where the content page is located. This means that you won't have to switch url's when deploying to live.
This method can also be applied to any element, not just a stylesheet or javascript file.
This Hack is part of the ASP.NET Hacks collection


