« Writing a Windows 8 Metro Hello World app using C#, XAML, and calling into a C++ component | Synchronization in async C# methods » |
Parsing URI query strings in Windows 8 metro-style apps
Tuesday, August 21, 2012
Take the URL string http://example.com/?a=foo&b=bar&c=baz
. 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; [TestClass] public class Tests { [TestMethod] public void TestWwwFormUrlDecoder() { Uri uri = new Uri("http://example.com/?a=foo&b=bar&c=baz"); WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(uri.Query); // named parameters Assert.AreEqual("foo", decoder.GetFirstValueByName("a")); // named parameter that doesn't exist Assert.ThrowsException<ArgumentException>(() => { decoder.GetFirstValueByName("not_present"); }); // 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]; }); } }
Comments
Williamben on Tuesday, April 29, 2025 at 08:37
Discover the secrets to achieving optimal wellness with our expert guidance. From mindful movement and natural skincare to gut health supplements and digital detox retreats, our comprehensive resource covers it all. Learn how to prioritize your mental health, boost your energy, and nourish your body with our actionable tips and expert advice. Whether you're looking to improve your sleep hygiene, optimize your fitness routine, or simply find a sense of calm, we've got you covered. Explore our curated content and start your journey towards a balanced, holistic lifestyle today!
<a href=https://wellness-warrior-guide.blogspot.com/2024/09/mindfulness-magic-easy-tricks-to-calm.html>Nutrition Advice</a>
Sandeep on Thursday, August 17, 2017 at 01:22
WebUtility can be used instead of WwwFormUrlDecoder