Converting a binary file to a string and vice versa

13,031

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.

Share:
13,031
Jan-Patrick Ahnen
Author by

Jan-Patrick Ahnen

Updated on June 06, 2022

Comments

  • Jan-Patrick Ahnen
    Jan-Patrick Ahnen almost 2 years

    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?