Wednesday, June 1, 2011

How to combine URLs with relative paths in C#

Many of us are familiar with the wonderful class System.IO.Path. It makes life a lot easier when working with file system paths, for example:

string filePath = System.IO.Path.Combine(@"c:\docs", @"important\", "myfirst.doc");

This results in in this path: c:\docs\important\myfirst.doc
This is handy when you need to combine a (part of the) path coming from a config file or as a parameter and you don't know for sure whether people work with trailing or leading slashes or not. The static methods of the Path class take care of that for us!

Now, I've been wondering for some time if there is a way to do something similar with URLs and relative paths. The easiest way to do this that I found is to use the constructor of the System.Uri class:

string webPath = new Uri(new Uri("http://www.delta-n.nl/"), @"\public\default.aspx").ToString();

This results in http://www.delta-n.nl/public/default.aspx. To be on the safe side, you could even better use the System.Uri.TryCreate(...) static method.

There is also a class called System.Web.VirtualPathUtility. However it works only with the paths from the current web app context and cannot be used for the above scenario.

Happy coding!

1 comment: