所以我试图在不使用LoadFile函数的情况下将文件加载到Richtextbox中,因为它不允许您指定编码。我也希望它可以分块加载,因此它不会使用太多内存。我尝试了多种方式,使用二进制读取器,streamreader等,但是我认为这是最好的解决方案。不幸的是,无论我做什么,每当我在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)
有人知道怎么了吗? 谢谢。