简体   繁体   中英

How to encode and decode special chars in C#

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)

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();
        }
    }
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM