Kirk Evans Blog

.NET From a Markup Perspective

base64 Encode XML Data

In a comment on my post on base64 decoding a picture in XML, someone asked (before the comment was deleted during the upgrade to Community Server until I learned where to find the comments in Community Server) how to do the opposite of that post.  That is, how do you base64 encode binary data into an XML document?

The key to doing this lies in the XmlTextWriter.WriteBase64() method.  This method accepts a byte array, so the only question left is how to convert a picture to a byte array?

In the example below, I load a GIF image from file into a System.Drawing.Image object.  To convert this to a byte array, I save the picture to an in-memory stream, which in turn can be read into a byte array using the System.IO.Stream.ToArray() method.  Once we have the byte array, we simply pass it to the XmlTextWriter.WriteBase64() method.

//Load the picture from a file
Image picture = Image.FromFile(@”c:\temp\test.gif”);

//Create an in-memory stream to hold the picture’s bytes
System.IO.MemoryStream pictureAsStream = new System.IO.MemoryStream();

//Rewind the stream back to the beginning
pictureAsStream.Position = 0;
//Get the stream as an array of bytes
byte [] pictureAsBytes = pictureAsStream.ToArray();

//Create an XmlTextWriter to write the XML somewhere… here, I just chose
//to stream out to the Console output stream

System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Console.Out);

//Write the root element of the XML document and the base64 encoded data



Note that I did not write out the complete Word 2003 XML document, I leave that as an exercise to the reader.  The key part is seeing how to write the base64 encoded data to the w:binData element.