How to convert to base64 in C #?

4

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

I'm used to using PHP and I use the base64_encode and base64_decode functions to do the base64 conversions.

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 duplicate, I did not find anything referring to it in the site

    
asked by anonymous 02.03.2018 / 17:32

2 answers

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

E

It does not 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 do not have to use a string for this.

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

string imagecodificadaembase64 = <valor em string do arquivo ou requisição em bas64>;
byte[] imagemdecodificada = System.Convert.FromBase64String(imagecodificadaembase64);
    
02.03.2018 / 17:49
2

I've taken 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);
}
    
02.03.2018 / 17:42