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
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:
StringBuilder
if you want to create one final string out of lots of bits, and you don't know how many bits in advanceText
propertySystem.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 exampleIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With