Skip to content

Reading a file byte by byte

Sebastian Harko

Asked May 4, 2007, 9:35 AM EDT1 answer
Share
LinkedInX
Hello everyone,

I'm trying to do an hex editor in C#. My plan is to read a file byte by byte and display the byte in a text box.

I have the code bellow but it works very slow. Does anyone know why it works so slow ??

C#
/// <summary>
/// Opens a file chooser.
/// </summary>
///
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog.ShowDialog();
string fileName = openFileDialog.FileName;
FileStream fileReader = new FileStream(fileName, FileMode.Open, FileAccess.Read);
long length = fileReader.Length;
long position = 0;

while (position < length){
position++;
textBox.Text += fileReader.ReadByte() + "  ";
}

}


Best regards

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    TextBox's Text property is a string.  Everytime you use += you create a new string to concat the new byte.  It can slow down your application if you read a lot of bytes.  Maybe you can use a StringBuilder

    StringBuilder buffer = new StringBuilder();
    while (position < length){
      position++;
      buffer.Append(fileReader.ReadByte() + "  ");
    }
    textBox.Text = buffer.ToString();

    of Course you can do something like this: 

    byte[] byteArray=new byte[length];
    fileReader.Read(byteArray, 0, length);
    textBox.Text = System.Text.ASCIIEncoding.ASCII.GetString(byteArray);

    but this give you a string without the spaces that you want between bytes and be carefully
    with System.Text.ASCIIEncoding.ASCII.GetString()
    0