c# - 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)
有人知道出了什么问题吗?谢谢。
解决方案
推荐阅读
- microsoft-graph-api - 图形邮件 API:504 网关超时错误
- groovy - 获取从节点可到达的顶点(在可变深度)
- regex - 使用字段分隔符在 bash 中替换 Perl 字符串 - 跳过标题行
- java - 为什么 getName 不包含在 java.lang.reflect.AccessibleObject 接口中?
- python - 对数曲线拟合不适合我的数据
- javascript - 未捕获的 ReferenceError: jQuery 未定义 Laravel
- python - 如何使用 __str__ 方法打印列表?
- python - 行 PySpark 数据框中的联合行
- elasticsearch - 如何在弹性搜索中选择不同的孩子
- android - 交换片段而不是替换?