m-u
9/17/2013 - 12:29 PM

Convert a NameValueCollection to a Querystring

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;
}