How to convert to base64 in C#?

I'm using WebForms. There is a certain part of this application where I send, through Ajax, a base64 string, which is the code of an image.

I am used to using PHP and I use the functions base64_encode and base64_decode to make the conversions to base64.

But in C # I have no idea how to do this.

How to decode a base64 in C # (and vice versa)?

I do not know if it is duplicated, I did not find anything referring to this on the site

 4
Author: Wallace Maxters, 2018-03-02

2 answers

If the code is about image manipulation then in C# it will not use string, will use byte[] probably, then the use of:

And

Doesn't make much sense, assuming you're going to read the image like this:

byte[] imagem = System.IO.File.ReadAllBytes(@"<caminho da imagem>");

Then just pass the variable like this:

string imagebase64 = System.Convert.ToBase64String(imagem);

You don't have to use string for this.

To decode you should use System.Convert.FromBase64String which will return in byte[] and then you can save the values of this in a file, just as you wish, example:

string imagecodificadaembase64 = <valor em string do arquivo ou requisição em bas64>;
byte[] imagemdecodificada = System.Convert.FromBase64String(imagecodificadaembase64);
 3
Author: Guilherme Nascimento, 2018-03-02 16:55:38

I took from here

Encode

public static string Base64Encode(string plainText) {
  var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  return System.Convert.ToBase64String(plainTextBytes);
}

Decode

public static string Base64Decode(string base64EncodedData) {
  var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
  return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
 2
Author: Leonardo Alves Machado, 2018-03-02 16:42:52