Parsing URI query strings in Windows 8 metro-style apps

Tuesday, August 21, 2012

Take the URL string How do we parse its query parameters using C# to get a dictionary or other key-value data structure?

In .NET, you can use HttpUtility.ParseQueryString(), but that function isn't present in WinRT APIs. Fortunately, there is a replacement: WwwFormUrlDecoder. The code below demonstrates its capabilities:

using System;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using Windows.Foundation;

public class Tests
    public void TestWwwFormUrlDecoder()
        Uri uri = new Uri("");
        WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(uri.Query);

        // named parameters
        Assert.AreEqual("foo", decoder.GetFirstValueByName("a"));

        // named parameter that doesn't exist
        Assert.ThrowsException<ArgumentException>(() => {

        // number of parameters
        Assert.AreEqual(3, decoder.Count);

        // ordered parameters
        Assert.AreEqual("b", decoder[1].Name);
        Assert.AreEqual("bar", decoder[1].Value);

        // ordered parameter that doesn't exist
        Assert.ThrowsException<ArgumentException>(() => {
            IWwwFormUrlDecoderEntry notPresent = decoder[3];

Tags: metro, winrt, csharp | Posted at 15:36 | Comments (0)


There are no comments.

Add a comment

Email: (optional, not displayed to public)