Hi, I’m using MS VS 2010 C#.NET, I’m trying to read a file from disk and send the BaseStream to a textbox on one of my Forms. Below is my code. It's working, but it’s doing so very, very slowly. A 16KB file took about 15 minutes to read and send to the textbox. A 10 KB file took close to 4 minutes to process. I’m sure I’m doing something wrong and I’m sure there’s a much more efficient manner to do so.
If you'd like to create the Form, its simply a Button named "btnRead" and multiline Textbox named "tbxText", with a vertical scroll-bar and its Font set to Courier New." You can use any text file you'd like for testing.
Can anyone help me to increase the efficiency of this code?
public partial class Form1 : Form
// Checks for file. If it exists, it reads it.
private void btnRead_Click(object sender, EventArgs e)
string path = @"C:\TestData\testfile.txt";
string fileLength = "";
string strBuffer = "";
Console.WriteLine("Started at : " + DateTime.Now);
Console.WriteLine("The file exists");
StreamReader sr = new StreamReader(File.OpenRead (path));
fileLength = sr.BaseStream.Length.ToString();
byte buffer = new byte[(long)sr.BaseStream.Length];
sr.BaseStream.Position = 0;
sr.BaseStream.Read(buffer, 0, ((int)sr.BaseStream.Length));
int i = 0;
foreach ( byte myByte in buffer)
strBuffer += myByte.ToString("X2") + " ";
tbxText.Text = strBuffer;
Console.WriteLine("The file does NOT exists");
Console.WriteLine("Ended at : " + DateTime.Now);