0

I have created an application in which I need to encode/decode special characters from the url which is entered by user.

For example : if user enters http://en.wikipedia.org/wiki/Å then it's respective Url should be http://en.wikipedia.org/wiki/%C3%85.

I made console application with following code.

string value = "http://en.wikipedia.org/wiki/Å";
Console.WriteLine(System.Web.HttpUtility.UrlEncode(value));

It decodes the character Å successfully and also encodes :// characters. After running the code I am getting output like : http%3a%2f%2fen.wikipedia.org%2fwiki%2f%c3%85 but I want http://en.wikipedia.org/wiki/%C3%85

What should I do?

asked May 8, 2014 at 11:10

2 Answers 2

1

Uri.EscapeUriString(value) returns the value that you expect. But it might have other problems.

There are a few URL encoding functions in the .NET Framework which all behave differently and are useful in different situations:

  1. Uri.EscapeUriString
  2. Uri.EscapeDataString
  3. WebUtility.UrlEncode (only in .NET 4.5)
  4. HttpUtility.UrlEncode (in System.Web.dll, so intended for web applications, not desktop)
answered May 8, 2014 at 11:36
0

You could use regular expressions to select hostname and then urlencode only other part of string:

var inputString = "http://en.wikipedia.org/wiki/Å";
var encodedString;
var regex = new Regex("^(?<host>https?://.+?/)(?<path>.*)$");
var match = regex.Match(inputString);
if (match.Success)
 encodedString = match.Groups["host"] + System.Web.HttpUtility.UrlEncode(match.Groups["path"].ToString());
Console.WriteLine(encodedString);
answered May 8, 2014 at 11:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.