tags:

views:

24

answers:

1

Hi,

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?

+4  A: 

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.

Jon Skeet
Thanks, works just the way it should!
Satanlike