tags:

views:

143

answers:

3
+4  Q: 

url building

I need to build a URL with a query string in C#. What is the best approach to doing this? Right now, I'm using something like,

string url = String.Format("foo.aspx?{0}={1}&{2}={3}", "a", 123, "b", 456);

Is there a better, preferred approach?

+5  A: 

I think that is a good method if it's always know what parameters you have, if this is unknown at the time you could always keep a List<KeyValuePair<string,string>> with the key being the name and value being the value, then build the query string using a foreach loop like

StringBuilder sb = new StringBuilder();
foreach(KeyValuePair<string,string> q in theList)
{
 // build the query string here.
    sb.Append(string.format("{0}={1}&", q.Key, q.Value);
}

note: the code is not tested and has not been compiled, so it may not work exactly as is.

John Boker
That's the way I like. Also you could wrap it in function that takes Dictionary<string, string> or better <string,object>.
Migol
Key and Value need to be URL-parameter-encoded before being concatenated.
bobince
+5  A: 

I think you should be using Server.UrlEncode on each of the arguments so that you don't send any bad characters in the URL.

Jason Punyon
+1  A: 

I've written a neat little open source library for exactly these kinds of things. Check out WebBuddy, and in particular UriBuddy. The binaries are for Silverlight, but you can easily browse the source and rip whatever you need.

Here is how you'd call UriBuddy:

// Take a base url
Uri sample = new Uri("http://www.nytimes.com");

// some highly useful parameters
Dictionary<String, String> query = new Dictionary<string, string>
{
    {"param1","nice"},
    {"param2","code man"}

};


// create a new url using a chained style of coding
Uri newSample = sample
    .AppendPath("/pages/world")
    .AppendQueryValues(query);

BTW, I've never had to do this kind of stuff outside of Silverlight. I'm fairly sure the "real" .NET library has built-in functions that look very similar to mine.

Cory R. King