Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace special characters in a URL?

Tags:

c#

url

encoding

This is probably very simple, but I simply cannot find the answer myself :(

Basicaly, what I want is, given this string:

"http://www.google.com/search?hl=en&q=c# objects"

I want this output:

http://www.google.com/search?hl=en&q=c%23+objects

I'm sure there's some helper class somewhere buried in the Framework that takes care of that for me, but I'm having trouble finding it.

EDIT: I should add, that this is for a Winforms App.

like image 729
BFree Avatar asked Feb 10 '09 18:02

BFree


People also ask

How do you change the special characters in a URL?

URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

What is the process of replacing reserved characters in a URL called?

However, if you reference objects or content store locations in your URL commands, you must replace illegal characters with their hexadecimal code equivalents, preceded by a percent sign. This is known as URL encoding.

Can you have special characters in a URL?

There are only certain characters that are allowed in the URL string, alphabetic characters, numerals, and a few characters ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) # that can have special meanings.


3 Answers

HttpServerUtility.UrlEncode(string)

Should sort out any troublesome characters

To use it you'll need to add a reference to System.Web (Project Explorer > References > Add reference > System.Web)

Once you've done that you can use it to encode any items you wish to add to the querystring:

System.Web.HttpUtility.UrlEncode("c# objects");
like image 163
Wilfred Knievel Avatar answered Oct 04 '22 07:10

Wilfred Knievel


If you don't want a dependency on System.Web here is an implementation of "UrlEncode" I have in my C# OAuth Library (which requires a correct implementation - namely spaces should be encoded using percent encoding rather the "+" for spaces etc.)

private readonly static string reservedCharacters = "!*'();:@&=+$,/?%#[]";

public static string UrlEncode(string value)
{
    if (String.IsNullOrEmpty(value))
        return String.Empty;

    var sb = new StringBuilder();

    foreach (char @char in value)
    {
        if (reservedCharacters.IndexOf(@char) == -1)
            sb.Append(@char);
        else
            sb.AppendFormat("%{0:X2}", (int)@char);
    }
    return sb.ToString();
}

For reference http://en.wikipedia.org/wiki/Percent-encoding

like image 41
Shiv Kumar Avatar answered Oct 04 '22 09:10

Shiv Kumar


@Wilfred Knievel has the accepted answer, but you could also use Uri.EscapeUriString() if you wanted to avoid the dependency on the System.Web namespace.

like image 36
dthrasher Avatar answered Oct 04 '22 07:10

dthrasher