Skip to content

Instantly share code, notes, and snippets.

@umair-me
Last active December 23, 2015 06:19
Show Gist options
  • Save umair-me/6593692 to your computer and use it in GitHub Desktop.
Save umair-me/6593692 to your computer and use it in GitHub Desktop.
Convert a NameValueCollection to a Querystring
/// <summary>
/// Constructs a NameValueCollection into a query string.
/// </summary>
/// <remarks>Consider this method to be the opposite of "System.Web.HttpUtility.ParseQueryString"</remarks>
/// <param name="parameters">The NameValueCollection</param>
/// <param name="delimiter">The String to delimit the key/value pairs</param>
/// <returns>A key/value structured query string, delimited by the specified String</returns>
public static string ToQueryString(this NameValueCollection parameters, String delimiter, Boolean omitEmpty)
{
if (String.IsNullOrEmpty(delimiter))
delimiter = "&";
Char equals = '=';
List<String> items = new List<String>();
for (int i = 0; i < parameters.Count; i++)
{
foreach (String value in parameters.GetValues(i))
{
Boolean addValue = (omitEmpty) ? !String.IsNullOrEmpty(value) : true;
if (addValue)
items.Add(String.Concat(parameters.GetKey(i), equals, HttpUtility.UrlEncode(value)));
}
}
return String.Join(delimiter, items.ToArray());
}
//much easier:
public static string ToQueryString(this NameValueCollection parameters)
{
var items = parameters.AllKeys
.SelectMany(parameters.GetValues, (k, v) => k + "=" + HttpUtility.UrlEncode(v))
.ToArray();
return String.Join("&", items);
}
HttpContext context = HttpContext.Current;
string formValues = "";
for (int i = 0; i < context.Request.Form.Count; i++)
{
string strValues = "";
foreach (var strValue in context.Request.Form.GetValues(context.Request.Form.Keys[i]))
{
strValues += strValue + ",";
}
formValues += context.Request.Form.Keys[i] + " - " + strValues + Environment.NewLine;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment