Recently I was working on a project where I needed to strip the scheme, host and port (if it wasn’t 80) from a Uri object. Obviously I could have used string concatenation to get the value I needed, but it just seemed so ghastly and inelegant. In frustration and annoyance that it wasn’t part of the standard Uri object definition, I asked a friend who gave me this little gem:
Uri uri = new Uri("http://localhost:6767/h/ello.php"); string url = new Uri(uri.AbsoluteUri).GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
The string, ‘url’, will (in this example) hold the value “http://localhost:6767”. This works in .Net 2.0 and up, and with .Net 3.0, you could even create a static method extension to make it even easier.