Formatting or Padding Bytes

Hi, I'm using MS Visual Studio C# 2010. I am trying to read a file into a textbox as a Binary String. My code is at the end of this question.

My question is... when I get to bytes that are single digits like "0" or "A", I only get one digit printing out, rather than two. Such as below:

6C 79 2E D A 0 0 0 0 0 0 0 0 0

How should I format or pad my output, so it prints out as show below?

6C 79 2E 0D 0A 00 00 00 00 00 00 00 00 00


Code:
private void btnRead_Click(object sender, EventArgs e)
        {
            string path = @"F:\Mary had a little Lamb.txt";

            if (File.Exists(path))
            {
                Console.WriteLine("The file exists");
                StreamReader sr = new StreamReader(File.OpenRead (path));
                byte[] buffer = new byte[1000];
                sr.BaseStream.Read(buffer, 0, 1000);
                foreach ( byte myByte in buffer)
                {
                    tbxText.Text += myByte.ToString("X") + " ";
                }
             
                sr.Dispose();
            }
            else
            {
                Console.WriteLine("The file does NOT exists");
            }

Open in new window

Mr_FulanoAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
wdosanjosConnect With a Mentor Commented:
Try:

tbxText.Text += myByte.ToString("X2") + " ";
0
 
James AtkinSenior Principle Software EngineerCommented:
Hi,

Try this:

    tbxText.Text += myByte.ToString("X").PadLeft(2, '0') + " ";

It will pad using the char specified

Hope this helps,

James
0
 
James AtkinSenior Principle Software EngineerCommented:
Hi,

The PadLeft function actually performs the length test for you. The length specified in the call is the TOTAL length of the resulting string.

i.e.
"AA" would return "AA"
"A" would return "0A"

Regards,

James
0
 
Mr_FulanoAuthor Commented:
Thank you both for your great replies. Although James was first to respond, Wdosanjos had the best approach. Thank you again for your help!

Fulano
0
 
Mr_FulanoAuthor Commented:
Very good and effective approach.
0
All Courses

From novice to tech pro — start learning today.