Help with string.format - building URL

Jason  picture Jason · Feb 14, 2011 · Viewed 13.2k times · Source

I am trying to use String.Format to help with building a URL that will hold a parameter from a local variable. I think i'm close, but not sure where to go from here.

Thanks, Jason

 string link=string.format("<A HREF="http://webserver/?x={0}&y={1}">Click here</A>",variable1,variable2 )

Answer

Darin Dimitrov picture Darin Dimitrov · Feb 14, 2011

You need to escape the double quotes:

string link = string.Format("<A HREF=\"http://webserver/?x={0}&y={1}\">Click here</A>", variable1, variable2);

This being said if you really want to generate valid HTML with valid urls I would recommend you the following:

var kvp = HttpUtility.ParseQueryString(string.Empty);
kvp["x"] = variable1;
kvp["y"] = variable2;
var uriBuilder = new UriBuilder("http", "webserver", 80);
uriBuilder.Query = kvp.ToString();
var anchor = new TagBuilder("a");
anchor.Attributes["href"] = uriBuilder.ToString();
anchor.SetInnerText("Click here");
string link = anchor.ToString();