Tim
Tim

Reputation: 952

string to byte[] conversion using XmlWriter and XmlReader

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>

Upvotes: 0

Views: 2355

Answers (1)

Khalil Khalaf
Khalil Khalaf

Reputation: 9407

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();
        }
    }
}

Upvotes: 2

Related Questions