Created
November 15, 2011 08:50
-
-
Save madd0/1366487 to your computer and use it in GitHub Desktop.
Create a URL query string from a NameValueCollection in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var nvc = new NameValueCollection | |
{ | |
{ "key1", "value1" }, | |
{ "key2", "value2" }, | |
{ "key3", "" } | |
}; | |
var builder = new UriBuilder("http://www.example.com"); | |
// Create query string with all values | |
builder.Query = string.Join("&", nvc.AllKeys.Select(key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key])))); | |
// Omit empty values | |
builder.Query = string.Join("&", nvc.AllKeys.Where(key => !string.IsNullOrWhiteSpace(nvc[key])).Select(key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key])))); |
@theShiva, since .NET 4.5 you can use System.Net.WebUtility
, which is in the System.dll assembly.
You can use this class in portable library or WinRT/Windows Phone
I know this is old but I thought I would update with a version that takes multiple querystring values into account to be compliant with the RFC:
uri.Query = string.Join("&",
nvc.AllKeys.Where(key => !string.IsNullOrWhiteSpace(nvc[key]))
.Select(
key => string.Join("&", nvc.GetValues(key).Select(val => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(val))))));
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there a way to do this without dependency on HttpUtility? I need something like this in a class library's Helper class.
Also, have you tried this with duplicate key names? NameValueCollection allows duplicate keys and another requirement of mine is that the NameValueCollection I have can contain duplicate keys.