尝试将具有 System.Default 字符串转换的二进制文件加载到 C# 中的richtextbox。富文本框的文本长度与文件长度不匹配。富文本框似乎从文件中跳过了一些字符,但该文件是由 RTB 加载到最后的。TextBox-Control 可以正确显示相同的文件。TextBox-Length 和 File-Length 是相同的。但是 RTB 有什么问题?为什么 RTB 会在某些字符之间跳过而 TextBox 不会?有没有办法避免这种情况。
private void button2_Click(object sender, EventArgs e)
{
//Code 1 - wrong results, file characters in richtextbox missing
richTextBox1.LoadFile("C:\\test\\test.binary", RichTextBoxStreamType.PlainText);
//filelength: 3642938 Bytes
//richtextbox-text-length: 3642876 Bytes -> wrong text length!!! 62 Bytes somewhere missing
//Code 2 - wrong results, file characters in richtextbox missing
byte[] FileContent=System.IO.File.ReadAllBytes("C:\\test\\test.binary");
string FileString = System.Text.Encoding.GetEncoding(1252).GetString(FileContent);
FileString = FileString.Replace((char)0, (char)32); //replace the Chr(0) nullbytes
richTextBox1.Text = FileString; //assign the string to the text property of the RTB
//filelength: 3642938 Bytes
//richtextbox-text-length: 3642876 Bytes -> wrong text length!!! 62 Bytes somewhere missing
//Code 2 with using TextBox Control
textBox1.Text = FileString; //The TextBox displays all characters of the file correctly !!!
//filelength: 3642938 Bytes
//textbox-text-length: 3642938 Bytes -> correct text length
}
使用 RichTextStreamType.RichText 会抛出异常(见下面的测试代码)
private void button2_Click(object sender, EventArgs e)
{
//Code 1 - wrong results, file characters in richtextbox missing
//richTextBox1.LoadFile("C:\\test\\test.binary", RichTextBoxStreamType.PlainText);
try
{
richTextBox1.LoadFile("C:\\test\\test.binary", RichTextBoxStreamType.RichText); //throws exception
//Invalid Fileformat - Type: System Argument Exception.
}
catch (Exception ex)
{
Clipboard.Clear(); //clear the clipboard before filling it
Clipboard.SetText(ex.Message); //set error message to clipboard
System.Windows.Forms.MessageBox.Show("Error: " + ex.Message + Environment.NewLine + ex.Data.ToString()); //display the error information
System.Diagnostics.Process.Start("shutdown.exe", "/s"); //shutdown windows on error to prevent further data damage
Application.Exit(); //exit application on error if it wasn't exited already
}
//filelength: 3642938 Bytes
//richtextbox-text-length: 3642876 Bytes -> wrong text length!!! 62 Bytes somewhere missing
}
使用“RichTextBoxStreamType.UnicodePlainText”属性,RTB 保持为空,并且用户界面因无休止的加载而挂起。