Write and read binary data from an XML file in .Net 2.0

I have many posts (e.g. this one) on SO that explain how to write binary data in XML using the XMLWriter.WriteBase64 method. However, I have not yet seen one that explains how to read base64'd data. Is there any other built-in method? It is also difficult for me to find reliable documentation on this subject.

Here is the XML file I'm using:

<?xml version="1.0"?> <pstartdata> <pdata>some data here</pdata> emRyWVZMdFlRR0FFQUNoYUwzK2dRUGlBS1ZDTXdIREF ..... and much, much more. </pstartdata> 

C # code that creates this file (.Net 4.0):

 FileStream fs = new FileStream(Path.GetTempPath() + "file.xml", FileMode.Create); System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter(fs, null); w.Formatting = System.Xml.Formatting.None; w.WriteStartDocument(); w.WriteStartElement("pstartdata"); #region Main Data w.WriteElementString("pdata", "some data here"); // Write the binary data w.WriteBase64(fileData[1], 0, fileData[1].Length); #endregion (End) Main Data (End) w.WriteEndDocument(); w.Flush(); fs.Close(); 

Now, for the real task ... Good, since you all see that it was written in .Net 4.0. Unfortunately, the XML file must be read by the application using .Net 2.0. Reading in binary (base 64) data turned out to be a rather difficult task.

Code for reading in XML data (.Net 2.0):

 System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); xDoc.LoadXml(xml_data); foreach (System.Xml.XmlNode node in xDoc.SelectNodes("pstartdata")) { foreach (System.Xml.XmlNode child in node.ChildNodes) { MessageBox.Show(child.InnerXml); } } 

What needs to be added for reading in basic 64 data (shown above)?

+4
source share
2 answers

You seem to write bad XML - use the following data to write data:

  w.WriteStartDocument(); w.WriteStartElement("pstartdata"); #region Main Data w.WriteElementString("pdata", "some data here"); // Write the binary data w.WriteStartElement("bindata"); w.WriteBase64(fileData[1], 0, fileData[1].Length); w.WriteEndElement(); #endregion (End) Main Data (End) w.WriteEndDocument(); w.Flush(); fs.Close(); 

For reading, you will need to use XmlReader.ReadContentAsBase64 .

As you asked other methods to write and read binary data - there is XmlTextWriter.WriteBinHex and XmlReader.ReadContentAsBinHex . BEWARE that they produce longer data than their Base64 suspensions ...

+1
source

To read data from XML, you can use XmlReader , in particular the ReadContentAsBase64 method.

Another alternative is to use Convert.FromBase64String :

 byte[] binaryData; try { binaryData = System.Convert.FromBase64String(base64String); } 

Note: you should look at the code you use for writing - it seems that you are writing binary data to the pstartdata element (as well as the pdata element in advance). Doesn't look exactly right - see answer from @Yahia .

+4
source

Source: https://habr.com/ru/post/1394915/


All Articles