Better way to get the Scheme, Host and Port from Uri Object in .Net

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:

side effect of clomid

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.