Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Uri.HexEscape(Char) Method in C#
The Uri.HexEscape() method in C# converts a specified character into its hexadecimal equivalent representation using percent-encoding. This method is particularly useful for URL encoding where certain characters need to be represented in hexadecimal format for safe transmission in URIs.
Syntax
Following is the syntax −
public static string HexEscape(char ch);
Parameters
ch − The character to convert to hexadecimal representation.
Return Value
Returns a string containing the hexadecimal representation of the character in the format %XX, where XX is the two-digit hexadecimal value.
Using HexEscape for Lowercase Characters
Example
using System;
public class Demo {
public static void Main() {
char ch = 'k';
string res = Uri.HexEscape(ch);
Console.WriteLine("Character: " + ch);
Console.WriteLine("Hexadecimal Equivalent = " + res);
// Show ASCII value for reference
Console.WriteLine("ASCII Value: " + (int)ch);
}
}
The output of the above code is −
Character: k Hexadecimal Equivalent = %6B ASCII Value: 107
Using HexEscape for Uppercase Characters
Example
using System;
public class Demo {
public static void Main() {
char ch = 'P';
string res = Uri.HexEscape(ch);
Console.WriteLine("Character: " + ch);
Console.WriteLine("Hexadecimal Equivalent = " + res);
// Show ASCII value for reference
Console.WriteLine("ASCII Value: " + (int)ch);
}
}
The output of the above code is −
Character: P Hexadecimal Equivalent = %50 ASCII Value: 80
Using HexEscape for Special Characters
Example
using System;
public class Demo {
public static void Main() {
char[] specialChars = {' ', '@', '&', '?', '#'};
Console.WriteLine("Special Character Hex Encoding:");
foreach(char ch in specialChars) {
string hexValue = Uri.HexEscape(ch);
Console.WriteLine($"'{ch}' ? {hexValue} (ASCII: {(int)ch})");
}
}
}
The output of the above code is −
Special Character Hex Encoding: ' ' ? %20 (ASCII: 32) '@' ? %40 (ASCII: 64) '&' ? %26 (ASCII: 38) '?' ? %3F (ASCII: 63) '#' ? %23 (ASCII: 35)
Common Use Cases
-
URL Encoding − Converting special characters for safe URL transmission.
-
Query String Parameters − Encoding values that contain reserved characters.
-
File Path Encoding − Converting characters that are not allowed in file names or paths.
Conclusion
The Uri.HexEscape() method provides a simple way to convert individual characters to their percent-encoded hexadecimal representation. This is essential for URL encoding and ensuring proper character handling in web applications and URI processing.
