问题
Hi i have read this question :
Reading very large text files, should I be incorporating async?
I diged the net especially the STACK OVERFLOW !
The results was 14 method to do this but none of them is not complete !
In 2 last days , i am working on this and tested and benchmarked 14 methods.
for example :
private void method()
{
FileStream FS = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
int FSBytes = (int) FS.Length;
int ChunkSize = 24;
byte[] B = new byte[ChunkSize];
int Pos;
for (Pos = 0; Pos < (FSBytes - ChunkSize); Pos += ChunkSize)
{
FS.Read(B,0 , ChunkSize);
string content = System.Text.Encoding.Default.GetString(B);
richTextBox1.Text=content=;
}
B = new byte[FSBytes - Pos];
FS.Read(B,0, FSBytes - Pos);
string content2 = System.Text.Encoding.Default.GetString(B);
richTextBox1Text=content2;
FS.Close();
FS.Dispose();
}
for 5mb text file , it takes too long , what should i do ?
回答1:
This is a working example of reading a text file per stream to accomplish what you are trying to do. I have tested it with a 100 MB text file, and it worked well, but you have to see if larger files work as well.
This is the example. Just bring a RichTextBox to your form and a VScrollBar. Then use a file 'test.txt' on your hard drive 'C:'.
public partial class Form1 : Form
{
const int PAGE_SIZE = 64; // in characters
int position = 0; // position in stream
public Form1()
{
InitializeComponent();
}
private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
position = e.NewValue * PAGE_SIZE;
ReadFile(position);
}
private void ReadFile(int position)
{
using (StreamReader sr = new StreamReader(@"C:\test.txt"))
{
char[] chars = new char[PAGE_SIZE];
sr.BaseStream.Seek(position, SeekOrigin.Begin);
sr.Read(chars, 0, PAGE_SIZE);
string text = new string(chars);
richTextBox1.Text = text;
}
}
private void Form1_Load(object sender, EventArgs e)
{
ReadFile(position);
}
}
来源:https://stackoverflow.com/questions/18113513/read-text-file-chunks-by-chunks-by-scrollbar