Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RichTextBox and special chars c#

I need to put text with RTF format in a richtextbox, I try to put it with the richtextbox.rtf = TextString parameter, but the problem is that the string has special chars and the richtextbox does not show all the string correctly. The String and code that I am using:

String (TextString):

╔═══This is only an example, the special characters may change═══╗

C# Code:

String TextString = System.Text.Encoding.UTF8.GetString(TextBytes);
String TextRTF = @"{\rtf1\ansi " + TextString + "}";
richtextbox1.Rtf = TextRTF;

With this code, richtextbox show "+---This is only an example, the special characters may change---+" and in some cases, show "??????".

How can i solve this problem? if i change \rtf1\ansi to \rtf1\utf-8, i not see changes.

like image 698
Manux22 Avatar asked Feb 01 '26 23:02

Manux22


1 Answers

You can simply use the Text property:

richTextBox1.Text = "╔═══This is only an example, the special characters may change═══╗";

If you want to use the RTF property: Take a look at this question: How to output unicode string to RTF (using C#)

You need to use something like this to convert the special characters to rtf format:

static string GetRtfUnicodeEscapedString(string s)
{
    var sb = new StringBuilder();
    foreach (var c in s)
    {
        if(c == '\\' || c == '{' || c == '}')
            sb.Append(@"\" + c);
        else if (c <= 0x7f)
            sb.Append(c);
        else
            sb.Append("\\u" + Convert.ToUInt32(c) + "?");
    }
    return sb.ToString();
}

Then use:

richtextbox1.Rtf = GetRtfUnicodeEscapedString(TextString);
like image 122
Jerry Avatar answered Feb 03 '26 12:02

Jerry