0

I've a RFC 3986 encoded string in the form %x##. For example the space character is encoded as %x20 instead of %20. How can I decode it in C#? Using the decode method of Uri, HttpUtility or WebUtility classes the string was not decoded.

Community
  • 1
  • 1
Matteo
  • 233
  • 3
  • 18
  • does this help: https://stackoverflow.com/questions/846487/how-to-get-uri-escapedatastring-to-comply-with-rfc-3986. its a possible duplicate – Gauravsa Jan 09 '20 at 10:18
  • A space (ascii 20) was not allowed so it was replaced with the encoded string. – jdweng Jan 09 '20 at 10:21

2 Answers2

1

You can try regular expressions in order to Replace all %x## as well as %## matches:

  using System.Text.RegularExpressions;

  ...

  string demo = "abc%x20def%20pqr";

  string result = Regex.Replace(
      demo, 
    "%x?([0-9A-F]{2})", 
      m => ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(), 
      RegexOptions.IgnoreCase);

  Console.Write(result);

Outcome:

  abc def pqr
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

You can try something like this: You can try:

Reference: How to get Uri.EscapeDataString to comply with RFC 3986

    var escapedString = new StringBuilder(Uri.EscapeDataString(value));

    for (int i = 0; i < UriRfc3986CharsToEscape.Length; i++) {
        escapedString.Replace(UriRfc3986CharsToEscape[i], Uri.HexEscape(UriRfc3986CharsToEscape[i][0]));
    }

    // Return the fully-RFC3986-escaped string.
    return escaped.ToString();
Gauravsa
  • 6,330
  • 2
  • 21
  • 30