Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render special character C#

I have a string that has special characters like this example: 12345678912\rJ\u0011 because I need to have access to this special chars to configure my application. I want to display this string exactly like this in a TextBox field so everything I have tried so far results in a string where the character \u0011 tries to render with an empty character at the end: "7896104866061\rJ".

I made this but it doesn't work.

string result = Regex.Replace(
    ToLiteral(this.Buffer), 
   "[^\x00-\x7Fd]", 
    c => string.Format("\\u{0:x4}", (int)c.Value[0]))
 .Replace(@"\", @"\\");

public static string ToLiteral(string input)
    {
        using (var writer = new StringWriter())
        {
            using (var provider = CodeDomProvider.CreateProvider("CSharp"))
            {
                provider.GenerateCodeFromExpression(
                    new CodePrimitiveExpression(input), 
                    writer, 
                    null);

                return writer.ToString();
            }
        }
    }

What need I do? Thanks in advance.

like image 618
regisls Avatar asked Jun 05 '19 11:06

regisls


1 Answers

Here my snippet to display ctrl chars: https://gist.github.com/TheTrigger/6efa6a8e42eedf1e61e0db8e9ef4360a

using System.Text;

namespace CtrlCharReplace
{
    public static class Extensions
    {
        public static string ReplaceCtrl(this string s)
        {
            var sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s[i];

                var isCtrl = char.IsControl(c);
                var n = char.ConvertToUtf32(s, i);

                if (isCtrl)
                {
                    sb.Append($"\\u{n:X4}");
                }
                else
                {
                    sb.Append(c);
                }
            }

            return sb.ToString();
        }
    }
}
like image 191
Fabio Avatar answered Nov 04 '22 17:11

Fabio