How to parse a query string into a NameValueCollection in .NET

Nathan Smith picture Nathan Smith · Sep 16, 2008 · Viewed 137k times · Source

I would like to parse a string such as p1=6&p2=7&p3=8 into a NameValueCollection.

What is the most elegant way of doing this when you don't have access to the Page.Request object?

Answer

Guy Starbuck picture Guy Starbuck · Sep 16, 2008

There's a built-in .NET utility for this: HttpUtility.ParseQueryString

// C#
NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);
' VB.NET
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)

You may need to replace querystring with new Uri(fullUrl).Query.