4

I have inherited some C# code. This code needs to upload a picture to a web service. This code saves the bytes of picture into byte[] called ImageBytes. To ensure the greatest portability, I want to first encode the ImageBytes into a base 64 encoded string. I believe the following code is doing that, however, I'm not sure. Can someone please verify if my assumption is correct?

StringBuilder sb = new StringBuilder();
this.ImageBytes.ToList<byte>().ForEach(x => sb.AppendFormat("{0}.", Convert.ToUInt32(x)));

Is this code converting my byte[] into a base 64 encoded string?

Thank you!

user609886
  • 1,639
  • 4
  • 25
  • 38
  • No, it will just give you all the bytes in decimal (base 10) with dots between them, like `162.239.5.104.86.`. Just as if you had said `String.Join(".", this.ImageBytes)`. – Jeppe Stig Nielsen Aug 04 '12 at 15:23

3 Answers3

11

use methods System.Convert.ToBase64String() and System.Convert.FromBase64String() for example

public static string EncodeTo64(string toEncode)
{
   byte[] toEncodeAsBytes = Encoding.ASCII.GetBytes(toEncode);
   return Convert.ToBase64String(toEncodeAsBytes);
}

public static string DecodeFrom64(string encodedData)
{
  byte[] encodedDataAsBytes = Convert.FromBase64String(encodedData);
  return Encoding.ASCII.GetString(encodedDataAsBytes);
}
burning_LEGION
  • 13,246
  • 8
  • 40
  • 52
2

Use the Convert.ToBase64String() method. It takes a byte array as parameter and returns the converted string.

Luis Aguilar
  • 4,331
  • 6
  • 36
  • 55
1

No, that's just converting it to a list of integers.

Use Convert.ToBase64String(). Assuming ImageBytes is a byte[]:

var base64Output = Convert.ToBase64String(ImageBytes);
Sean U
  • 6,730
  • 1
  • 24
  • 43