
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Converting a String Returned as a Byte[ ] Back into a String
|
57
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 = Base64DecodeString(bmpAsString);
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.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.
2.13 Converting a String Returned as a Byte[ ] Back
into a String
Problem
Many methods in the FCL return a byte[] because they are providing a byte stream
service, but some applications need to pass strings over these byte stream services.
Some of these methods include:
System.Diagnostics.EventLogEntry.Data
System.IO.BinaryReader.Read
System.IO.BinaryReader.ReadBytes
System.IO.FileStream.Read
System.IO.FileStream.BeginRead
System.IO.MemoryStream ...