Search code examples
c#.netnamevaluecollection

Encode values in a NameValueCollection C# .net


I have a name value collections which is passed into a method to send to another system via a web client.

public string DoExtendedTransferAsString(string operation, NameValueCollection query, FormatCollection formats)
{
    System.Net.WebClient client = new System.Net.WebClient();
    client.QueryString = query;
    client.QueryString["op"] = operation;
    client.QueryString["session"] = SessionId;
    using (Stream stream = client.OpenRead(url))
    {
        FormatCollection formats = new FormatCollection(stream);
    }
    return formats;
}

I need to run HttpUtility.HtmlEncode on all the values inside the NameValueCollection but I am unsure how to. NB I cannot change the calling code so it have to be a NameValueCollection.

Thanks


Solution

  • try this

    myCollection.AllKeys
        .ToList()
        .ForEach(k => myCollection[k] = 
                HttpUtility.HtmlEncode(myCollection[k]));