Does anyone have a good example of how to use this method? All of the MSDN examples I could find are useless because:

  1. they show a hard-coded size for the byte array
  2. they show writing the output to the Console

Ridiculous. I have a file that contains some binary image data (PCL format) that is base64 encoded. I simply need to read that, decode it back to raw binary, and write it out to a file.

All my attempts run, but do not produce usable output.

Dani AI

Generated

Short answer: stream the decoded bytes straight to a FileStream in a loop, using the XmlReader/XmlTextReader base64 helpers and writing only the number of bytes returned each iteration. For large embedded images you should prefer an XmlReader created with XmlReader.Create; if you must use XmlTextReader, the ReadBase64 method still works. See the API docs: XmlTextReader.ReadBase64 and XmlReader.ReadElementContentAsBase64. (learn.microsoft.com)

Example pattern (streaming; no full-string allocation):

using (XmlReader reader = XmlReader.Create(xmlPath))
{
    if (reader.ReadToFollowing(elementName))
    {
        using (FileStream outFs = new FileStream(outPath, FileMode.Create))
        {
            byte[] buffer = new byte[8192];
            int read;
            while ((read = reader.ReadElementContentAsBase64(buffer, 0, buffer.Length)) > 0)
            {
                outFs.Write(buffer, 0, read);
            }
        }
    }
}

The code above uses the streaming ReadElementContentAsBase64 loop and writes exactly read bytes each pass (critical). See the XmlReader example in the docs. (learn.microsoft.com)

Notes and troubleshooting (what usually goes wrong):

  • Make sure the reader is positioned on the element content (use ReadToFollowing, ReadStartElement, or check NodeType).
  • Write only the count returned by ReadElementContentAsBase64 / ReadBase64; writing the whole buffer will corrupt output.
  • Some XmlReader implementations/contexts do not implement the element-level helpers; if so you can fall back to reading the element text and calling Convert.FromBase64String, but that allocates the whole decoded byte array in memory (OK for small payloads). See Convert.FromBase64String remarks. (learn.microsoft.com)
  • Be aware of whitespace/newline handling and reader positioning; in some cases an extra final ReadElementContentAsBase64 (or the do/while pattern) is required so the reader advances correctly. (stackoverflow.com)

(Thanks to for the clear problem description; ’s pointer to Convert.FromBase64String is useful for small payloads but streaming with XmlReader is safer for large images.) (learn.microsoft.com)

What about having a look at Convert.ToBase64String and Convert.FromBase64String ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.