1

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 が空のままになり、ユーザー インターフェイスがエンドレス ロードでハングします。

4

0 に答える 0