Store Binary Data with a Base64 Transform

Problem

You need to store binary data in an XML file.

Solution

Use Convert.ToBase64String to create a string representation of the data that will not contain any illegal characters.

Discussion

XML documents can’t contain extended characters, or special characters such as the greater than (>) or less than (<) symbols, which are used to denote elements. However, you can convert binary data into a string representation that is XML-legal by using a Base64 transform.

In Base64 encoding, each sequence of three bytes is converted to a sequence of four bytes. Each Base64 encoded character has one of the 64 possible values in the range {A-Z, a-z, 0-9, +, /, =}.

Here’s an example that creates a new node in the orders.xml ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.