简体   繁体   中英

Converting a binary file to a string and vice versa

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?

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM