There comes a time when you need to get the absolute path to reference a file or some resource existing at some relative path of the website or web application. As things turned i was in need some of the similar functionality. The first thing that came to my mind was doing something similar :
//get the absolute path for the following relative path String relPath = @"~/ImageResource/ImageName.jpg"; Control cntrl = new Control(); String absPath = cntrl.ResolveClientUrl(relPath);
As it is this works great, but i wanted something more elegant, which doesnt involve the creation of the Control object. So i searched for sometime and stumbled upon an unknown utility function available, right over in .NET framework. Interesting to know that there so many useful functionality in-built in .NET framework which rarely are seen in practice.
Ok then about this utility API is called VirtualPathUtility and it is contained in the System.Web namespace. So using the VirtualUtilityPath you can rewrite the above piece of code as follows
//get the absolute path for the following relative path String relPath = @"~/ImageResource/ImageName.jpg"; String absPath =VirtualPathUtility.ToAbsolute(relPath);
Nice little function. But beware there are some pitfalls you need to avoid. This function is not one size fits all solution. You need to be aware of some of shortfalls described in some of the posts below. But for simple use, this works great.
| Related Posts |
| MSDN: VirtualPathUtility Class |
| Weblogs.asp.net: VirtualPathUtility Class |
| How VirtualPathUtility combines paths in .Net 2.0 – level 100 |
Filed under: C#, Dot Net, How To, Technical | Leave a Comment »
