How to convert to Base64 in C#?

Asked

Viewed 1,662 times

4

I am using Webforms. There is a certain part of this application where I send, through Ajax, a string Base64, which is the code of an image.

I’m used to using PHP and use the functions base64_encode and base64_decode to make the conversions to Base64.

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

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

I don’t know if it’s duplicate, I didn’t find anything related to it on the site

2 answers

3


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

And

They don’t make much sense, supposing I read the picture like this:

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

So just pass the variable like this:

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

You don’t have to use string for this.

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

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

2

I took it 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

    Assuming it is in UTF8 and is string this ok ... if it is in another format you have to be careful with this, it is not a solution that works magically, for example, for non-Unicode it would probably be System.Text.ASCIIEncoding.ASCII.GetBytes, for binary data would probably already use bytes directly (after all, Base64 is usually for carrying binary data)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.