so I'm trying to load a file into a richtextbox without using the LoadFile function, as it does not allow you to specify an Encoding. I also want it to load in chunks, so it does not use as much memory. I have tried MANY ways, using a binary reader, streamreader, etc, but I think this is the best solution. Unfortunately, no matter what I do, whenever I compare the original file and the loaded file in Notepad++, there always seems to be extra lines in the text file. I thought it was a problem with reading the file, and I did a test to find it out. I have the input file stream and output file, and they were exactly the same! However, when I append the text in the richtextbox, a few extra lines appear.
Here is the code:
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)
Does anybody know what's wrong? Thanks.