예제 #1
0
        /// <summary>
        /// Join the name-value pairs into a string seperated with ampersands.
        /// Each name and value is first RFC 3986 encoded and values are separated
        /// from names with equal signs.
        /// </summary>
        /// <param name="values">The name value collection to encode and join</param>
        /// <returns>An RFC 3986 compliant string</returns>
        public static string EncodeAndJoin(NameValueCollection values)
        {
            if (values == null)
            {
                return(string.Empty);
            }

            StringBuilder enc = new StringBuilder();

            bool first = true;

            foreach (string key in values.Keys)
            {
                string encKey = Rfc3986.Encode(key);
                foreach (string value in values.GetValues(key))
                {
                    if (!first)
                    {
                        enc.Append("&");
                    }
                    else
                    {
                        first = false;
                    }

                    enc.Append(encKey).Append("=").Append(Rfc3986.Encode(value));
                }
            }

            return(enc.ToString());
        }
예제 #2
0
        /// <summary>
        /// Splits a ampersand-separated list of key-value pairs, decodes the keys and
        /// values, and adds them to a NameValueCollection. Keys and values are separated
        /// by equals signs.
        /// </summary>
        /// <param name="input">The key-value pair list</param>
        /// <returns>A name value collection, which may be empty.</returns>
        /// <exception cref="System.FormatException">
        /// If the string is not a series of key-value pairs separated by ampersands,
        /// or if one of the keys is null or empty, or if one of the keys or values is
        /// not properly encoded.
        /// </exception>
        public static NameValueCollection SplitAndDecode(string input)
        {
            NameValueCollection parameters = new NameValueCollection();

            if (string.IsNullOrEmpty(input))
            {
                return(parameters);
            }

            foreach (string pair in input.Split('&'))
            {
                string[] parts = pair.Split('=');

                if (parts.Length != 2)
                {
                    throw new FormatException("Pair is not a key-value pair");
                }

                string key = Rfc3986.Decode(parts[0]);
                if (string.IsNullOrEmpty(key))
                {
                    throw new FormatException("Key cannot be null or empty");
                }

                string value = Rfc3986.Decode(parts[1]);

                parameters.Add(key, value);
            }

            return(parameters);
        }