danielwertheim

danielwertheim


notes from a passionate developer

Developer that lives by the mantra "code is meant to be shared".

Share


Tags


Disclaimer

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

Daniel WertheimDaniel Wertheim

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:steel@my-sub.my-domain.com:8081/todo/list/?foo=bar");

var values = Enum.GetValues(typeof (UriComponents)).OfType();  
foreach (var value in values)  
{
    Console.WriteLine("{0} = {1}",
        value,
        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:steel@my-sub.my-domain.com:8081/todo/list/?foo=bar  
StrongPort = 8081  
HostAndPort = my-sub.my-domain.com:8081  
StrongAuthority = superman:steel@my-sub.my-domain.com:8081  
NormalizedHost = my-sub.my-domain.com  
KeepDelimiter =  
SerializationInfoString = https://superman:steel@my-sub.my-domain.com:8081/todo/list/?foo=bar  

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

Console.WriteLine(uri.GetComponents(  
    UriComponents.AbsoluteUri &
    ~UriComponents.UserInfo &
    ~UriComponents.Port &
    ~UriComponents.Path, UriFormat.UriEscaped));

Which outputs:

https://my-sub.my-domain.com?foo=bar  

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.

//Daniel

Developer that lives by the mantra "code is meant to be shared".

Comments