How to encode and decode special chars in C#

11,592

Solution 1

Html encoding/decoding seemed to work for me:

using System;
using System.Net;

namespace StackOverflow_EncodingSpecialCharacters
{
    class Program
    {
        static void Main(string[] args)
        {
            const string input = @"trmp % al1 €haced£rs Àc17ç";
            Console.WriteLine($"Input:  \t{input}");

            string encoded = WebUtility.HtmlEncode(input);
            Console.WriteLine($"Encoded: \t{encoded}");

            string output = WebUtility.HtmlDecode(encoded);
            Console.WriteLine($"Output: \t{output}");

            Console.ReadKey();
        }
    }
}

Solution 2

Also, under the System.Web assembly :

            string decoded = System.Web.HttpUtility.HtmlDecode(input);
            string encoded = System.Web.HttpUtility.HtmlEncode(input);

// similar for URLs (like converting the space to plus sign, etc.)
            string urldecoded = System.Web.HttpUtility.UrlDecode(url);
            string urlencoded = System.Web.HttpUtility.UrlEncode(url);
Share:
11,592
RaceBase
Author by

RaceBase

#SOreadytohelp

Updated on June 04, 2022

Comments

  • RaceBase
    RaceBase almost 2 years

    I have text with special chars trmp %al1 €haced£rs Àc17ç.

    Consider that the channel through which I pass the data doesn't support these special chars and the destination needs to decode the encoded text to get original data.

    I tried looking at Base64 encoding,decoding or HTML encoding/decoding and nothing seems to retain the same data.

    The source and destination are C# process (supports these charset)