encode uri component in csharp

To encode a URI component in C#, you can use the System.Uri.EscapeDataString(string) method. This method takes a string as input and returns the escaped version of that string that can be safely used within a URI.

main.cs
string unescapedString = "Hello, world!";
string escapedString = Uri.EscapeDataString(unescapedString);
Console.WriteLine(escapedString); // Output: Hello%2C%20world%21
169 chars
4 lines

In this example, we first define a string unescapedString with the value "Hello, world!". We then call Uri.EscapeDataString(unescapedString) to obtain the escaped version of the string, and store the result in escapedString. Finally, we print the escaped string to the console.

Note that the EscapeDataString method will escape all characters that are not safe to include in a URI component, including spaces, commas, and exclamation points, as well as any non-ASCII characters that are not in the URI character set.

related categories

gistlibby LogSnag