2.9. Decoding a Base64-Encoded Binary
Problem
You have a String that contains information such as a bitmap encoded as base64. You need to decode this data (which may have been embedded in an email message) from a String into a byte[] so that you can access the original binary.
Solution
Using the static method Convert.FromBase64String on the Convert class, an encoded String may be decoded to its equivalent byte[]:
using System;
static class CharStrExtMethods
{
public static byte[] Base64DecodeString(this string inputStr)
{
byte[] decodedByteArray =
Convert.FromBase64String(inputStr);
return (decodedByteArray);
}
}Discussion
The static FromBase64String method on the Convert class makes decoding an encoded base64 string a simple matter. This method returns a byte[] that contains the decoded elements of the String.
If you receive a file via email, such as an image file (.bmp), that has been converted to a string, you can convert it back into its original bitmap file using something like the following:
byte[] imageBytes = bmpAsString.Base64DecodeString();
using (FileStream fstrm = new FileStream(@"C:\winnt_copy.bmp",
FileMode.CreateNew, FileAccess.Write))
{
using (BinaryWriter writer = new BinaryWriter(fstrm))
{
writer.Write(imageBytes);
}
}In this code, the bmpAsString variable was obtained from the code in the Discussion section of Recipe 2.10. The imageBytes byte[] is the bmpAsString String converted back to a byte[], which can then be written back to disk.
To encode a byte[] to a String ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access