5

I get a url string and would like to transform it to a legal http url:

For example:

"http://one/two/three%four/five#five?six seven" should turn into "http://one/two/three%25four/five%23five?six%20seven"

However, HttpUtility.UrlEncode does not help, as it encodes the entire string (including the legal "://").

2 Answers 2

4

See if this what you want?

   Uri uri = new Uri("http://one/two/three%four/#five?six seven");
   string url = uri.AbsoluteUri + uri.Fragment; 
   // url will be "http://one/two/three%25four/#five?six%20seven#five?six%20seven"
1
  • Is this solution valid for any URL? May 6, 2011 at 14:03
0

How about splitting and rejoining:

string url = "http://one/two/three%four/#five?six seven";
string encodedUrl = "http://" + string.Join("/", url.Substring(7).Split('/').Select(part => HttpUtility.UrlEncode(part)).ToArray());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.