Tuesday, February 5, 2008

Parsing a URI / URL in C# and VB.NET

I used to spend time parsing a URL string using old fashion .NET string methods. (Contains, Split, Substring, IndexOf, etc). I always thought, "There must be a better way to do this."

And there is, there is a tool in the .NET Framework to help you parse a fully qualified URI path.

System.UriBuilder

A few simple lines of code

2008-02-06_0508

Does a lot of the work for us.

2008-02-06_0507 

And this is just one of the Uri tools. I encourage you to look at the others as well.

  • System.Uri
  • System.UriComponents
  • System.UriFormat
  • System.UriHostNameType
  • System.UriIdnScope
  • System.UriKind
  • System.UriParser
  • System.UriPartial
  • System.UriTypeConverter

4 comments:

  1. So does this mean I need to re-write my HTML utility?

    ReplyDelete
  2. As always a genius, and not only in your own mind!

    ReplyDelete
  3. Add HttpUtility.ParseQueryString(uri.Query) to the mix and you've got everything you need.

    ReplyDelete
  4. @rouftop Now why didn't I think of that? Awesome suggestion!

    ReplyDelete