Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting bytes to a string C#

Tags:

c#

I want to convert a binary file to a string which could be then converted back to the binary file. I tried this:

byte[] byteArray = File.ReadAllBytes(@"D:\pic.png");
for (int i = 0; i < byteArray.Length; i++)
{
    textBox1.Text += (char)byteArray[i];
}

but it's too slow, it takes about 20 seconds to convert 5KB on i5 CPU. I noticed that notepad does the same in much less time. Any ideas on how to do it?

Thanks

like image 403
Ephi Gabay Avatar asked Feb 10 '12 15:02

Ephi Gabay


1 Answers

If you want to be able to convert back to binary without losing any information, you shouldn't be doing this sort of thing at all - you should use base64 encoding or something similar:

textBox1.Text = Convert.ToBase64String(byteArray);

You can then convert back using byte[] data = Convert.FromBase64String(text);. The important thing is that base64 converts arbitrary binary data to known ASCII text; all byte sequences are valid, all can be round-tripped, and as it only requires ASCII it's friendly to many transports.

There are four important things to take away here:

  • Don't treat arbitrary binary data as if it were valid text in a particular encoding. Phil Haack wrote about this in a blog post recently, in response to some of my SO answers.
  • Don't perform string concatenation in a loop; use a StringBuilder if you want to create one final string out of lots of bits, and you don't know how many bits in advance
  • Don't use UI properties in a loop unnecessarily - even if the previous steps were okay, it would have been better to construct the string with a loop and then do a single assignment to the Text property
  • Learn about System.Text.Encoding for the situation where you really have got encoded text; Encoding.UTF8.GetString(byteArray) would have been appropriate if this had been UTF-8-encoded data, for example
like image 115
Jon Skeet Avatar answered Sep 24 '22 02:09

Jon Skeet