Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a binary file to a string and vice versa

Tags:

c#

.net

encoding

I created a webservice which returns a (binary) file. Unfortunately, I cannot use byte[] so I have to convert the byte array to a string. What I do at the moment is the following (but it does not work):

Convert file to string:

byte[] arr = File.ReadAllBytes(fileName);
System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();  
string fileAsString = enc.GetString(arr);  

To check if this works properly, I convert it back via:

System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();
byte[] file = enc.GetBytes(fileAsString);

But at the end, the original byte array and the byte array created from the string aren't equal. Do I have to use another method to read the file to a byte array?

like image 375
Jan-Patrick Ahnen Avatar asked Dec 29 '22 08:12

Jan-Patrick Ahnen


1 Answers

Use Convert.ToBase64String to convert it to text, and Convert.FromBase64String to convert back again.

Encoding is used to convert from text to a binary representation, and from a binary representation of text back to text again. In this case you don't have a binary representation of text - you just have arbitrary binary data... so Encoding is inappropriate. Even if you use an encoding which can "sort of" handle any binary data (e.g. ISO Latin 1) you'll find that many ways of transmitting text will fail when you've got control characters etc.

Base64 encoding will give you text which is just ASCII, and much easier to handle.

like image 73
Jon Skeet Avatar answered Jan 13 '23 11:01

Jon Skeet