Parse Query String - CSharp System.Net

CSharp examples for System.Net:IP Address

Description

Parse Query String

Demo Code

// Redistribution and use in source and binary forms, with or without modification,
using System.Linq;
using System;//from   w  ww. jav a 2  s  . com
using System.Collections.Generic;

public class Main{
        public static Dictionary<string, string> ParseQueryString(this Uri uri)
        {
            Dictionary<string, string> query = new Dictionary<string, string>();
            
            try
            {                                
                string[] parts = uri.Query.Split(new char[] {'?','&'});
                foreach (string part in parts)
                {
                    if (!string.IsNullOrEmpty(part))
                    {
                        string[] nameValue = part.Split(new char[] {'='});
                        if (nameValue != null)
                        {
                            query.Add(nameValue[0].ToLower(), nameValue[1]);
                        }
                    }
                }
            }
            catch(System.Exception e)
            {
                throw new Exception("Unable to parse URI query string", e);
            }
            
            return query;
        }
}

Related Tutorials