given is an URL like http://localhost:1973/Services.aspx?idProject=10&idService=14
.
What is the most straightforward way to replace both url-parameter values(for example 10 to 12 and 14 to 7)?
Regex, String.Replace, Substring or LinQ - i'm a little stuck.
Thank you in advance,
Tim
I ended with following, that's working for me because this page has only these two parameter:
string newUrl = url.Replace(url.Substring(url.IndexOf("Services.aspx?") + "Services.aspx?".Length), string.Format("idProject={0}&idService={1}", Services.IdProject, Services.IdService));
But thank you for your suggestions :)
The most robust way would be to use the Uri class to parse the string, change te param values and then build the result.
There are many nuances to how URLs work and while you could try to roll your own regex to do this it could quickly get complicate handling all the cases.
All the other methods would have issues with substring matches etc and I don't even see how Linq applies here.
I have recently released UriBuilderExtended, which is a library that makes editing of query strings on
UriBuilder
objects a breeze through extension methods.You basically just create a
UriBuilder
object with your current URL string in the constructor, modify the query through the extension methods, and build the new URL string from theUriBuilder
object.Quick example:
URL string is obtained from
builder.Uri.ToString()
, notbuilder.ToString()
as it sometimes renders differently to what you'd expect.You can get the Library through NuGet.
More examples here.
Comments and wishes are most welcome.
This is what I would do:
Usage:
Or:
I have the same problem and i solved it with the following three lines of code that i get from the coments here (like Stephen Oberauer's solution, but less overenginieered):
This is the solution using VB .NET but the conversion to C# is strightforward.
The most straightforward way is
String.Replace
, but you'll end up with problems if your uri looks likehttp://localhost:1212/base.axd?id=12&otherId=12
the C# HttpUtility.ParseQueryString utility will do the heavy lifting for you. You will want to do some more robust null checking in your final version.