C# URL processing: getting parts of an URL easily with GetLeftPart()
Posted: (EET/GMT+2)
Sometimes, you need to process cleaned URLs with C# that don't include paths, filenames or query strings. While URLs can be processed as text, I much rather use the Uri or UriBuilder classes to process these.
Let's assume you have the following URL, and you want to get the host URL from it:
http://www.contoso.com/index.htm?date=today
Sure, you could do some string processing, but the Uri class contains a handy, though not perhaps ideally named method called GetLeftPart. This method gets a portion of the URL, starting from the left, up to the selected part: Scheme (protocol), Authority (host), Path or QueryString.
For example, if you would call:
string url = myUrl.GetLeftPart(UriPartial.Authority);
...on the above URL, it would return:
http://www.contoso.com
If the URL had a port number, then that would be returned as well. Very handy indeed!