notes from a passionate developer





This is a personal blog. The opinions expressed here represent my own and not those of my employer, nor current or previous. All content is published "as is", without warranty of any kind and I don't take any responsibility and can't be liable for any claims, damages or other liabilities that might be caused by the content.

C# - Using bitwise combinations with Uri.GetComponents

Time to share something neath, and that is the possibility of using bitwise combinations of System.UriComponents (MSDN-docs) with System.Uri.GetComponents (MSDN-docs) to easily reformat an URL.

Lets have a look at some code that dumps out the individual values of an URL and finally makes use of GetComponents to “pick some parts of interest”.

var uri = new Uri(
    "https://superman:[email protected]:8081/todo/list/?foo=bar");

var values = Enum.GetValues(typeof (UriComponents)).OfType();
foreach (var value in values)
    Console.WriteLine("{0} = {1}",
        uri.GetComponents(value, UriFormat.UriEscaped));

The output of the code above:

Scheme = https
UserInfo = superman:steel
Host = my-sub.my-domain.com
Port = 8081
SchemeAndServer = https://my-sub.my-domain.com:8081
Path = todo/list/
Query = foo=bar
PathAndQuery = /todo/list/?foo=bar
HttpRequestUrl = https://my-sub.my-domain.com:8081/todo/list/?foo=bar
Fragment =
AbsoluteUri = https://superman:[email protected]:8081/todo/list/?foo=bar
StrongPort = 8081
HostAndPort = my-sub.my-domain.com:8081
StrongAuthority = superman:[email protected]:8081
NormalizedHost = my-sub.my-domain.com
KeepDelimiter =
SerializationInfoString = https://superman:[email protected]:8081/todo/list/?foo=bar

Now lets look at how we can make use of bitwise combinations, to remove: UserInfo, Port and Path

    UriComponents.AbsoluteUri &
    ~UriComponents.UserInfo &
    ~UriComponents.Port &
    ~UriComponents.Path, UriFormat.UriEscaped));

Which outputs:


As you can see, it removed: UserInfo, Port and Path so that only Scheme, Host and Query were left.

That’s all. A neat little solution to have in your toolbox.


View Comments