0

I have two methods XmlWriter and XmlReader.
I have a byte[] called Thumbprint. In the writer I convert it from a byte[] to a string and write it to my Xml file. This works. I need to figure out how to read it back in from a string and convert it back to a byte[].
Here is my code so far:

public void WriteXml(XmlWriter writer)
        {

            writer.WriteStartElement("agent");           


            writer.WriteStartElement("thumbprint");
            var encoding = new UnicodeEncoding();    
            if (Thumbprint != null)
            {
                string base64 = System.Convert.ToBase64String(encoding.GetBytes(Thumbprint.ToString()));
                writer.WriteCData(base64);
            }
            else
            { 
                writer.WriteEndElement();
            }
        }

public void ReadXml(XmlReader reader)
        {
            if (reader.IsStartElement("agent"))
            {    
                //
                // Read past <agent>
                //
                reader.Read();

                while (true)
                {
                    if (reader.IsStartElement("thumbprint"))
                    {
                         byte[] toDecodeByte = System.Convert.FromBase64String(Thumbprint.ToString());
                         Thumbprint = toDecodeByte;   
                    }
                    else
                    {
                        //
                        // Read </agent>
                        //
                        reader.MoveToContent();
                        reader.ReadEndElement();
                        break;
                    }
                }
            }
            else
            {
                throw new XmlException("Expected <agent> element was not present");
            }
        }

Xml Input:

<thumbprint>
    <![CDATA[UwB5AHMAdABlAG0ALgBCAHkAdABlAFsAXQA=]]>
</thumbprint>
Tim
  • 952
  • 3
  • 12
  • 31
  • Can we see a sample example of your XML file(the input)? – Khalil Khalaf Aug 01 '16 at 16:19
  • Sure. I added the Xml snippet to the OP. So far I tried to use the example from here: http://stackoverflow.com/questions/17835928/write-xml-in-base64-encoding but I can't seem to get this to work. I also tried a different way but that is not working either. If you look at the read method in the OP I have also updated with what I've tried. – Tim Aug 01 '16 at 16:27

1 Answers1

2

A general solution to convert from byte array to string when you don't know the encoding:

static string BytesToStringConverted(byte[] bytes)
{
    using (var stream = new MemoryStream(bytes))
    {
        using (var streamReader = new StreamReader(stream))
        {
            return streamReader.ReadToEnd();
        }
    }
}
Khalil Khalaf
  • 9,259
  • 11
  • 62
  • 104