Zach L
Zach L

Reputation: 1275

URLEncoding an Array of URLs .NET

I have an array with URLs like http://www.example.com?a=1 1&b=2 2&c=3 3 and I need to URL Encode each of the URLs.

But if I use HttpServerUtility.URLEncode(url) it would output http%3a%2f%2fwww.example.com%3fa%3d1+1%26b%3d2+2%26c%3d3+3, but I need it to look like http://www.example.com?a=1+1&b=2+2&c=3+3

Is there anyway to achieve this?

Also the parameter values may not only have a space, they could have an & sign.

Upvotes: 1

Views: 399

Answers (4)

Zach L
Zach L

Reputation: 1275

Thanks everyone for your responses, you helped me come up with an solution I could use.

        Dim sURL As String = "http://www.example.com?a=1 1&b=2 2&c=3 3"
    Dim sURLParameters = sURL.Split("?")
    Dim parameters As NameValueCollection

    parameters = HttpUtility.ParseQueryString(sURLParameters(1))

    sURL = sURLParameters(0) & "?"
    For i As Integer = 0 To parameters.Count - 1
        sURL += parameters.Keys(i).ToString & "=" & Server.UrlEncode(parameters.Item(i).ToString)
    Next

    Response.Write(sURL)

This link lead me into the ParseQueryString solution.

.Net C# regex for parsing URL parameters

Upvotes: 1

m.edmondson
m.edmondson

Reputation: 30892

You need to encode the individual elements NOT the whole string so the URL you would end up with is http://www.example.com?a=1%201&b=2%202&c=3%203.

Can you see how the spaces within have been converted to %20 but it was only the actual variables "1 1" "2 2" "3 3" which are actually input into HttpServerUtility.URLEncode()

Like Mitchel says this isn't going to be an out of the box solution but you could so some fiddling in order to extract these variables for UrlEncoding.

Upvotes: 0

Mark Avenius
Mark Avenius

Reputation: 13947

You can do this:

string oldUrl = "http://www.example.com?a=1 1&b=2 2&c=3 3"
string oldUrlSplit = oldUrl.Split('?');
string newUrl = oldUrlSplit[0] + HttpUtility.URLEncode(oldUrlSplit[1]);

Obviously, you want to null check, etc.

Edit:

I was slightly short of the ball on this one. You will also want to split your oldUrlSplit[1] on & and subsequently on =, after which point you will only URLEncode the latter part (after the =). Thanks to @Anthony Pegram for pointing this out.

Upvotes: 0

Mitchel Sellers
Mitchel Sellers

Reputation: 63126

There isn't going to be an out of the box method to do what you want to do. From a programmatic perspective, an & in a QueryString is not something that it is going to be able to setup.

Also, UrlEncoding a URL is setting it up to be sent via a URL, this is why it is going to replace the / and other characters.

Sure you could urlEncode the querystring, but that will most likely cause un-intended results.

Upvotes: 0

Related Questions