Come to the dark side...we have cookies!

Have you seen Uri.GetComponents()?

If you haven’t, it is freaking brilliant! Well, at least very useful! And it has been around since .NET 2.0…

For some reason I keep ending up in situations where I need to get certain parts of a Url. In a lot of cases, I just want to extract the scheme and host name, eg http://chris.59north.com/, from a longer Url, and I don’t think I am alone. But if you Google it to find a good solution, you get a gazillion hits talking about how people have created this awesome method that takes the parts of the Url and uses string concatenation to build the result. Well, guess what…that sucks!

I myself had not seen this method until recently when a colleague showed it to me, and to be honest I have no idea where he found it…

The way that it works, is that you basically take your Uri object and call GetComponents() passing in a bitwise combination of values from an enumeration called UriComponents. You also have to provide a UriFormat that defines how characters in the Uri are escaped…

The components that you can choose from are available here: http://bit.ly/pyKfh2

But to me, the most useful one would be UriComponents.SchemeAndServer which will give you exactly what I talked about earlier, but there are of course other components that might be useful for other scenarios.

Well, that was it for now…just thought I would mention it as I spent a while trying to find it again yesterday. I knew there was a method that did what I needed as I had been shown it before, but I couldn’t remember the name. And Google was most helpful in giving me string concatenation samples, but hard pressed to give me what I wanted…


Posted: Aug 25 2011, 08:19 by ZeroKoll | Comments (0) |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: .NET development
Manage post: :)
Comments are closed