Most of the time, when we are setting the image url, we will use "~" symbol before the image file name. I was wondering what is the meaing of "~" symbol and how it works? How does ASP.NET knows whether the website is running from the root of IIS or from a Virtual Directory? Then, translate this symbol into a correct URL?
For example, setting the image button image url to "~/images/ok.jpg". We will have 2 situations:
1. The website is running from the IIS root. This means, you will have
http://www.testing.com/images/ok.jpg
2. The website is running from a virtual directory in IIS. You will have
http://www.testing.com/news/images/ok.jpg
Programmatically, we have to use System.Web.VirtualPathUtility class to determine the URL of the image.
"~/images/ok.jpg"
- VirtualPathUtility.IsAbsolute() will returns false. Meaning, once the URL contains the "~" symbol, it becomes relative. So, VirtualPathUtility.IsAppRelative() will return true.
- For ASP.NET to translate this URL into a runtime URL, we have to call VirtualPathUtility.ToAbsolute(). The result will be "/images/ok.jpg" and "/news/images/ok.jpg" for the above mentioned situation respectively.
- To compute the physical path, you have to call AppDomain.CurrentDomain.BaseDirectory + relative path (you have to remove the "~" symbol and replace "/" with "\").
No comments:
Post a Comment