Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base 64 encoding in C#

Tags:

c#

encoding

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!

like image 246
user609886 Avatar asked Oct 28 '25 17:10

user609886


2 Answers

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);
}
like image 125
burning_LEGION Avatar answered Oct 31 '25 06:10

burning_LEGION


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

like image 21
Luis Aguilar Avatar answered Oct 31 '25 06:10

Luis Aguilar