
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
56
|
Chapter 2: Strings and Characters
{
using (BinaryReader reader = new BinaryReader(fstrm))
{
byte[] image = new byte[reader.BaseStream.Length];
for (int i = 0; i < reader.BaseStream.Length; i++)
{
image[i] = reader.ReadByte( );
}
}
}
string bmpAsString = Base64EncodeBytes(image);
The bmpAsString string can then be sent as the body of an email message.
To decode an encoded string to a
byte[], see Recipe 2.12.
See Also
See Recipe 2.12; see the “Convert.ToBase64CharArray Method” topic in the MSDN
documentation.
2.12 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;
public static byte[] Base64DecodeString(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.