P.Brian.Mackey
P.Brian.Mackey

Reputation: 44285

Treat url as c# object so I can split params

I want to use a console application to easily divide a URL from its params so I can URL encode the parameters. Is there a type that makes this simple? Please keep in mind that this is being run outside of a web server.

The URL is of the form

E.G.

string url = "http://sitename/folder1/someweb.dll?RetrieveTestByDateTime?PatientID=1234&param2=blah blah blah";

So then I can do

string finalUrl = "http://sitename/folder1/someweb.dll?RetriveTestByDateTime?PatientID=" + HttpUtility.UrlEncode(PatientIDValue) + HttpUtility.UrlEncode(param2Value);

Second, is the second ? valid? This data comes from a 3rd party app. Surely this can be accomplished with Regex, but I prefer not to use it as most people on my team do not know regular expressions.

Upvotes: 0

Views: 461

Answers (2)

Eric Herlitz
Eric Herlitz

Reputation: 26307

Firstly your url structure is bad

string url = "http://sitename/folder1/someweb.dll?RetrieveTestByDateTime?PatientID=1234&param2=blah blah blah";

should be

string url = "http://sitename/folder1/someweb.dll?RetrieveTestByDateTime&PatientID=1234&param2=blah blah blah";

A possible solution, I'm not in a development environment now so this is from the head. Some changes may need to be done to the code.

string url = "http://sitename/folder1/someweb.dll?RetrieveTestByDateTime&PatientID=1234&param2=blah blah blah";
var uri = new Uri(url);
var queryString = uri.Query;
NameValueCollection query = HttpUtility.ParseQueryString(queryString)
query["PatientID"] = string.Concat(HttpUtility.UrlEncode(PatientIDValue), HttpUtility.UrlEncode(param2Value));

// Rebuild the querystring
queryString = "?" + 
                 string.Join("&", 
                              Array.ConvertAll(query.AllKeys, 
                                                key => string.Format("{0}={1}", 
                                                HttpUtility.UrlEncode(key), 
                                                HttpUtility.UrlEncode(query[key]))));

Upvotes: 0

Oded
Oded

Reputation: 499212

Use the Uri class - pass in the string url to the constructor and it will parse out the different parts.

The query will be in the Query property and you can reconstruct the URL easily using the Scheme, AbsolutePath and the encoded Query.

Upvotes: 4

Related Questions