How can I parse HTTP urls in C#?

I think you can get a lot of use out of the System.Uri class. Feed it a URI and you can pull out pieces in a number of arrangements.

Some examples:

Uri myUri = new Uri("http://server:8080/func2/SubFunc2?query=somevalue");

// Get host part (host name or address and port). Returns "server:8080".
string hostpart = myUri.Authority;

// Get path and query string parts. Returns "/func2/SubFunc2?query=somevalue".
string pathpart = myUri.PathAndQuery;

// Get path components. Trailing separators. Returns { "https://stackoverflow.com/", "func2/", "sunFunc2" }.
string[] pathsegments = myUri.Segments;

// Get query string. Returns "?query=somevalue".
string querystring = myUri.Query;

Leave a Comment