2010-12-03 13 views
0

Webクライアントを介して別のシステムに送信するメソッドに渡される名前値のコレクションがあります。NameValueCollectionの値をエンコードするC#.net

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

私はNameValueCollectionの内側のすべての値でHttpUtility.HtmlEncodeを実行する必要がありますが、私はどのようにわからないと思います。注:NameValueCollectionでなければならないので、呼び出しコードを変更することはできません。 MSDNから

おかげ

+0

@Liviu Mは私が特定されていたと思った申し訳ありませんが、私はNameValueCollectionの中の値にこれをやってみたいしてみてください。私はしようとしました(int i = 0; i Cookie

答えて

3

この

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

このソリューションを使用している皆のためのFYIは、私が直ちに気づいたものではないlinqが必要です。 – Cookie

0

class MyNewClass 
    { 
     public static void Main() 
     { 
     String myString; 
     Console.WriteLine("Enter a string having '&' or '\"' in it: "); 
     myString=Console.ReadLine(); 
     String myEncodedString; 
     // Encode the string. 
     myEncodedString = HttpUtility.HtmlEncode(myString); 
     Console.WriteLine("HTML Encoded string is "+myEncodedString); 
     StringWriter myWriter = new StringWriter(); 
     // Decode the encoded string. 
     HttpUtility.HtmlDecode(myEncodedString, myWriter); 
     Console.Write("Decoded string of the above encoded string is "+ 
         myWriter.ToString()); 
     } 
    } 

あなたがのために/ foreachのループでは、コレクション内の各値の符号化の一部を行います。

これがあなたが探していたものでない場合は、質問にもっと明示してください。私は、これはあなたが望むものを達成すると思い

0

...

public string DoExtendedTransferAsString(string operation, NameValueCollection query, FormatCollection formats) 
    { 
     foreach (string key in query.Keys) 
     { 
      query[key] = HttpUtility.HtmlEncode(query[key]); 
     } 

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

注私はそこに追加foreachの、あなただけのキーを使用して各項目をつかみ、上HtmlEncodeを呼び出して、すべてのキーを反復処理していますそれを右に戻す。

+1

残念ながら私は取得できませんInvalidOperationException - 列挙子がインスタンス化された後にコレクションが変更されました。 – Cookie

関連する問題