Bill Gates
Bill Gates

Reputation: 857

Elegant way parsing URL

After POST/GET request I get such URL back which I need to parse, of course I can go and use spit() to get required information, but for sure should be more elegant way of doing that. Any ideas?

http://api.vkontakte.ru/blank.html#access_token=8860213c0a392ba0971fb35bdfb0z605d459a9dcf9d2208ab60e714c3367681c6d091aa12a3fdd31a4872&expires_in=86400&user_id=34558123

I am parsing for: access token and expires_in

Upvotes: 61

Views: 108708

Answers (4)

Martin Kunc
Martin Kunc

Reputation: 471

this is late to the party, but since .NET 6, there is

 Uri.TryCreate (string? uriString, UriKind uriKind, out Uri? result);

Which should help with parsing without exception.

More on MS Learn

Upvotes: 1

ryudice
ryudice

Reputation: 37366

Using the URI class you can do this:

var url = new Uri("your url");

Upvotes: 75

Blairg23
Blairg23

Reputation: 12045

There are several ways you can do this. One is that you can simply use the Uri.Query method to get the query string and then parse by the &s. Another is that you can use the Uri.Query method and then use HttpUtility.ParseQueryString to parse the query string as a NameValueCollection, which might be your preferred route.

See the example below:

using System.Web; // For HttpUtility

// The original URL:
Uri unparsedUrl = new Uri("http://api.vkontakte.ru/blank.html#access_token=8860213c0a392ba0971fb35bdfb0z605d459a9dcf9d2208ab60e714c3367681c6d091aa12a3fdd31a4872&expires_in=86400&user_id=34558123");
// Grabs the query string from the URL:
string query = unparsedUrl.Query; 
// Parses the query string as a NameValueCollection:
var queryParams = HttpUtility.ParseQueryString(query);

You can now perform operations similar to how you would deal with a Dictionary object. Like so:

string accessToken = queryParams["access_token"];
string expiresIn = queryParams["expires_in"];

This has the same functionality as what @Jeroen Bouman showed, but splits apart the different functions so you can understand what each piece does individually.

References:

Uri.Query

HttpUtility.ParseQueryString

NameValueCollection

Upvotes: 19

Jeroen Bouman
Jeroen Bouman

Reputation: 829

Use Uri + ParseQueryString functions:

Uri myUri = new Uri("http://api.vkontakte.ru/blank.html#access_token=8860213c0a392ba0971fb35bdfb0z605d459a9dcf9d2208ab60e714c3367681c6d091aa12a3fdd31a4872&expires_in=86400&user_id=34558123");

String access_token = HttpUtility.ParseQueryString(myUri.Query).Get("access_token");
String expires_in = HttpUtility.ParseQueryString(myUri.Query).Get("expires_in");

This will also do the trick

String access_token = HttpUtility.ParseQueryString(myUri.Query).Get(0);

Source: https://msdn.microsoft.com/en-us/library/ms150046.aspx

Tip: You might need

using System.Web;

And add a reference to System.Web

Upvotes: 62

Related Questions