Manipulating Querystrings in Csharp and .NET

A small library to help parse and manipulate querystring paramaters in C#

If you're an ASP.NET developer then sooner or later you will come across an occasion when you want to manipulate or parse values from the current request's querystring (the querystring being the name/value pairs you often see appended to URLs). The good news is that ASP.NET pages makes available the HttpRequest.QueryString property. The bad news is that this returns a read-only NameValueCollection that cannot be easily manipulated or even iterated over (you can't, for instance, use the foreach construct with a NameValueCollection). This means that parsing values in the querystring becomes a real chore.

To this end I developed a very small C# library (that can be downloaded below) that enables developers to easily manipulate the querystring collection. It has useful methods to add, remove, replace, count and parse values within a querystring. Instead of outlining all the methods in detail I will show a small code excerpt below that uses the library to perform a few common tasks. If you're like me, you'll find this way is the best way to grasp how it works.

Code Example

QueryStringHelper qsh = new QueryStringHelper("?page=5&username=dan&year=2010&enabled=true&email=dan@example.com");
string username = qsh.GetByName("username"); // username = "dan"
qsh.Add("category", "products"); // adds a new key called "category" with the value "products"
qsh.AddOrReplace("year", "1999"); // changes the year value from "2010" to "1999"
int year = qsh.GetByName<int>("year"); // year = 1999
qsh.AddOrReplace("page", 6); // changes the value of "page" to "6"
bool enabled = qsh.GetByName<bool>("enabled"); // enabled = true
qsh.RemoveByName("email"); // removes the "email" key
string qs = qsh.GetQueryString(); // qs = "page=6&username=dan&year=1999&enabled=true&category=products";
int count = qsh.Count(); // count = 5

Download Link

Diplo.QueryStringHelper
Posted: 04 November 2010 | Bookmark: Permalink | Comments: Post Comment | Follow: RSS Feed | Bookmark and Share |
Tagged: , | Topics: Technology_Internet | Social Tags: URL, Microsoft Visual Studio, Query string, Foreach, Parsing, Computing, ASP.NET, Template engines | Organisations: ASP.NET

Post a Comment

Please fill the form in below if you wish to add a comment:
Gravatar

Please don't post raw HTML - use editor above - otherwise you will get an error.