Strings and Characters, Part 1 - 2.12 Decoding a Base64-Encoded Binary
(Page 12 of 12 )
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.FromBase64CharArray on the Convert class, an encoded char[] and/or string may be decoded to its equivalent byte[]:
using System;
public static byte[] Base64DecodeString(string inputStr)
{
byte[] decodedByteArray =
Convert.FromBase64CharArray(inputStr.ToCharArray(),
0, inputStr.Length);
return (decodedByteArray);
}
Discussion The static FromBase64CharArray 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 previously been converted to a string, to convert it back into its original bitmap file, you could do something like the following:
byte[] imageBytes = Base64DecodeString(bmpAsString);
fstrm = new FileStream(@"C:\winnt_copy.bmp", FileMode.CreateNew, FileAccess.Write);
BinaryWriter writer = new BinaryWriter(fstrm);
writer.Write(imageBytes);
writer.Close();
fstrm.Close();
In this code, the bmpAsString variable was obtained from the code in the Discussion section of Recipe 2.11. 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, see Recipe 2.13.
See Also See Recipe 2.11;see the “Convert.FromBase64CharArray Method” topic in the MSDN documentation.
 | If you've enjoyed what you've seen here, or to get more information, click on the "Buy the book!" graphic. Pick up a copy today!
Visit the O'Reilly Network http://www.oreillynet.com for more online content. |
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |