4

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?

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.