首页 > 解决方案 > RichTextBox appendtext 有时会添加额外的行?

问题描述

所以我试图在不使用 LoadFile 函数的情况下将文件加载到富文本框中,因为它不允许您指定编码。我还希望它分块加载,因此它不会使用太多内存。我尝试了很多方法,使用二进制阅读器、流阅读器等,但我认为这是最好的解决方案。不幸的是,无论我做什么,每当我在 Notepad++ 中比较原始文件和加载的文件时,文本文件中似乎总是有多余的行。我以为是读取文件有问题,做了个测试才发现。我有输入文件流和输出文件,它们完全一样!但是,当我在richtextbox 中附加文本时,会出现一些额外的行。

这是代码:

    const int bufferSize = 16384;
    using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, FileOptions.SequentialScan))
                {
                    using (FileStream outStream = File.Create(@"C:\Users\me\Desktop\file comparison.txt"))
                    {
                        int bytesRead;
                        byte[] buffer = new byte[bufferSize];
                        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                            outStream.Write(buffer, 0, bytesRead);
                    }
                }
    //Result:
    //The 2 files are the same

    using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, FileOptions.SequentialScan))
                {
                    int bytesRead;
                    byte[] buffer = new byte[bufferSize];
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        if (bytesRead != bufferSize)
                            Array.Resize(ref buffer, bytesRead); //On the last chunk if the file is not a multiple of bufferSize (16384), it will leave some parts of the previous chunk behind
                        richTextBox.AppendText(Encoding.UTF8.GetString(buffer));
                    }
                }
//Result:
//When I copy and paste into notepad++ and compare the original and this, there are a few extra lines (empty lines)

有人知道出了什么问题吗?谢谢。

标签: c#.netwinformstextrichtextbox

解决方案


推荐阅读