WPF(C#)中API返回RTF转纯文本失败求助
Solution to Convert RTF Hex String to Plain Text in WPF/C#
Let’s walk through the exact steps to turn your hex-encoded RTF into plain text for display in WPF—this should fix the issues you’ve been hitting.
Step 1: Convert Hex String to Valid RTF
Your input is a hexadecimal representation of RTF bytes. First, we need to convert this hex string to a proper RTF string using the encoding specified in your RTF (ansicpg1252):
public static string HexToRtf(string hexString) { // Strip leading "0x" if present hexString = hexString.TrimStart('0', 'x'); // Convert hex to byte array byte[] rtfBytes = new byte[hexString.Length / 2]; for (int i = 0; i < hexString.Length; i += 2) { rtfBytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16); } // Decode using the codepage specified in your RTF (1252) return Encoding.GetEncoding(1252).GetString(rtfBytes); }
Step 2: Convert RTF to Plain Text
WPF’s built-in RichTextBox can handle RTF parsing even if you don’t display it. We’ll use it in memory to extract plain text:
public static string RtfToPlainText(string rtf) { using (var tempRichTextBox = new RichTextBox()) { var textRange = new TextRange(tempRichTextBox.Document.ContentStart, tempRichTextBox.Document.ContentEnd); using (var reader = new StringReader(rtf)) { textRange.Load(reader, DataFormats.Rtf); } return textRange.Text.Trim(); // Trim extra newlines/spaces from RTF formatting } }
Step 3: Put It All Together
Combine these methods to get your plain text and display it in your text control (note: WPF doesn’t have a TextView—I assume you mean TextBlock or TextBox):
// Your input hex RTF string string hexRtf = "0x7B5C727466315C616E73695C616E7369637067313235325C64656666305C6465666C616E67313033337B5C666F6E7474626C7B5C66305C666E696C5C666368617273657430204D6963726F736F66742053616E732053657269663B7D7D5C766965776B696E64345C7563315C706172645C66305C667331382068656C6C6F5C70617220207D"; // Convert hex to RTF string rtf = HexToRtf(hexRtf); // Convert RTF to plain text string plainText = RtfToPlainText(rtf); // Display in your text control yourTextBlock.Text = plainText; // Or yourTextBox.Text = plainText;
Why This Works
- Hex Conversion: We use the exact codepage (
1252) specified in your RTF, avoiding garbled text from mismatched encodings. - RTF Parsing: WPF’s native
TextRangeclass handles all RTF formatting rules, so you don’t have to manually parse complex RTF syntax.
Quick Troubleshooting
- If you get junk text, double-check that your hex string has no invalid characters (like spaces or non-hex digits).
- For WPF
TextBox, setAcceptsReturn="True"if you want to preserve line breaks from the RTF.
内容的提问来源于stack exchange,提问作者Nirav Joshi
相关产品推荐
相关产品推荐

