If you are like me, then you need to combine a base url path with another path to a web page or a service. Since base paths change often due to the application running from different environments, this is a common task. The .NET Framework provided use with a simple way of combining file paths, but not URL paths. This could be a nice addition to the Uri type.
Here is an easy way to combine URL paths:
public static string CombineUrlPaths(string basePath, string pagePath) { if (String.IsNullOrEmpty(basePath) || String.IsNullOrEmpty(pagePath)) { throw new ArgumentNullException((basePath == null) ? "path1" : "path2"); } if (pagePath[0] == char.Parse("/")) { pagePath = pagePath.Substring(1, pagePath.Length - 1); } var path = basePath[basePath.Length - 1] != char.Parse("/") ? (String.Format("{0}/{1}", basePath, pagePath)) : (basePath + pagePath); return path; }
Usage example:
CombineUrlPaths("http://dotnettips.com", "default.aspx"); CombineUrlPaths("http://dotnettips.com", "/default.aspx"); CombineUrlPaths("http://dotnettips.com/", "default.aspx");
Tip By: David McCarter
Path.Combine is handy, but there is no similar function in the .NET framework for combining Url or Uri.
https://uricombine.codeplex.com/
This project has one class Uri.cs which allows combining multiple parts to make a safe (encoded) Uri.