Get individual query parameters from Uri

C#.NetUri

C# Problem Overview


I have a uri string like: http://example.com/file?a=1&b=2&c=string%20param

Is there an existing function that would convert query parameter string into a dictionary same way as ASP.NET Context.Request does it.

I'm writing a console app and not a web-service so there is no Context.Request to parse the URL for me.

I know that it's pretty easy to crack the query string myself but I'd rather use a FCL function is if exists.

C# Solutions


Solution 1 - C#

Use this:

string uri = ...;
string queryString = new System.Uri(uri).Query;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);

This code by Tejs isn't the 'proper' way to get the query string from the URI:

string.Join(string.Empty, uri.Split('?').Skip(1));

Solution 2 - C#

You can use:

var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
System.Web.HttpUtility.ParseQueryString(queryString)

MSDN

Solution 3 - C#

This should work:

string url = "http://example.com/file?a=1&b=2&c=string%20param";
string querystring = url.Substring(url.IndexOf('?'));
System.Collections.Specialized.NameValueCollection parameters = 
   System.Web.HttpUtility.ParseQueryString(querystring);

According to MSDN. Not the exact collectiontype you are looking for, but nevertheless useful.

Edit: Apparently, if you supply the complete url to ParseQueryString it will add 'http://example.com/file?a'; as the first key of the collection. Since that is probably not what you want, I added the substring to get only the relevant part of the url.

Solution 4 - C#

I had to do this for a modern windows app. I used the following:

public static class UriExtensions
{
    private static readonly Regex _regex = new Regex(@"[?&](\w[\w.]*)=([^?&]+)");

    public static IReadOnlyDictionary<string, string> ParseQueryString(this Uri uri)
    {
        var match = _regex.Match(uri.PathAndQuery);
        var paramaters = new Dictionary<string, string>();
        while (match.Success)
        {
            paramaters.Add(match.Groups[1].Value, match.Groups[2].Value);
            match = match.NextMatch();
        }
        return paramaters;
    }
}

Solution 5 - C#

Have a look at HttpUtility.ParseQueryString() It'll give you a NameValueCollection instead of a dictionary, but should still do what you need.

The other option is to use string.Split().

    string url = @"http://example.com/file?a=1&b=2&c=string%20param";
    string[] parts = url.Split(new char[] {'?','&'});
    ///parts[0] now contains http://example.com/file
    ///parts[1] = "a=1"
    ///parts[2] = "b=2"
    ///parts[3] = "c=string%20param"

Solution 6 - C#

For isolated projects, where dependencies must be kept to a minimum, I found myself using this implementation:

var arguments = uri.Query
  .Substring(1) // Remove '?'
  .Split('&')
  .Select(q => q.Split('='))
  .ToDictionary(q => q.FirstOrDefault(), q => q.Skip(1).FirstOrDefault());

Do note, however, that I do not handle encoded strings of any kind, as I was using this in a controlled setting, where encoding issues would be a coding error on the server side that should be fixed.

Solution 7 - C#

In a single line of code:

string xyz = Uri.UnescapeDataString(HttpUtility.ParseQueryString(Request.QueryString.ToString()).Get("XYZ"));

Solution 8 - C#

Solution 9 - C#

You could reference System.Web in your console application and then look for the Utility functions that split the URL parameters.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGhostriderView Question on Stackoverflow
Solution 1 - C#Timothy ShieldsView Answer on Stackoverflow
Solution 2 - C#TejsView Answer on Stackoverflow
Solution 3 - C#pyrocumulusView Answer on Stackoverflow
Solution 4 - C#Ross DarganView Answer on Stackoverflow
Solution 5 - C#3DaveView Answer on Stackoverflow
Solution 6 - C#Johny SkovdalView Answer on Stackoverflow
Solution 7 - C#PabinatorView Answer on Stackoverflow
Solution 8 - C#Alex BedroView Answer on Stackoverflow
Solution 9 - C#RajView Answer on Stackoverflow