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 hidden or 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])))); |
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
@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