Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding an Underscore to %5F

Tags:

c#

asp.net

I am trying to use the HttpUtility.HtmlEncode to encode an underscore to %5f, but the encoded value does not give me the hex representation. How will I accomplish this?

string encodedValue = HttpUtility.HtmlEncode("First_Name");

The value I want in the encodedValue string is "First%5FName".

Is there something I am missing? I have also tried using the HttpUtility.UrlEncode, but that does not give me the desired result as well.

I know this should be something simple, but I cant get around it.

like image 598
TK1 Avatar asked Apr 29 '13 16:04

TK1


People also ask

Does underscore need to be URL encoded?

What is URL encoding or Percent Encoding? URLs in the world wide web can only contain ASCII alphanumeric characters and some other safe characters like hyphen ( - ), underscore ( _ ), tilde ( ~ ), and dot ( . ). Alphabets / Digits / "-" / "_" / "~" / "." Any other character apart from the above list must be encoded.

Is _ valid in URL?

A URL is composed from a limited set of characters belonging to the US-ASCII character set. These characters include digits (0-9), letters(A-Z, a-z), and a few special characters ( "-" , "." , "_" , "~" ).


2 Answers

if you just want to replace _ with %5f, you can just use myString.Replace("_", "%5f");

like image 95
Robert J. Avatar answered Oct 18 '22 14:10

Robert J.


It's an old subject but to convert a char in its HexEscape format you should use:

myString.Replace("_", Uri.HexEscape("_"));
like image 33
RizzCandy Avatar answered Oct 18 '22 15:10

RizzCandy