Click here to Skip to main content
15,942,292 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey guys have a little problem here, I have a varbinary column in my db that has a byte[] stored in it. I can save it out ok but when I try read it back out I get an error saying Data at the root level is invalid. Line 1, position 1.

C#
private void button2_Click(object sender, EventArgs e)
      {
          conn.Open();
          DataTable dt = GetXmlFileDataTable(conn);

          using(MemoryStream memStream = new MemoryStream((byte[])dt.Rows[0][0]))
          {
              memStream.Position = 0;
              byte[] array = memStream.ToArray();
              XDocument objXDoc = new XDocument();
              string xml = Encoding.UTF8.GetString(array);
              XDocument xmlDoc = XDocument.Parse(xml);
              string fileName = "VarBinary.xml";
              string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), fileName);
              xmlDoc.Save(path);
              memStream.Dispose();
          }
          //button1.Enabled = true;
          //button2.Enabled = false;
          conn.Close();
      }


Cheers guys
Posted

1 solution

Sounds like the XML is invalid, or you're missing the doctype. .Net XML libraries do seem to be a bit picky about that.

Also, memStream.Dispose isn't necessary, the using block will close it for you.
 
Share this answer
 
Comments
frostcox 17-May-12 10:31am    
What line should I include in the top for the doc type?
lewax00 17-May-12 10:35am    
<?xml version="1.0" encoding="utf-8" ?>
is generally sufficient
frostcox 17-May-12 10:37am    
Thats not working, keeps throwing the error, when I first load the byte[] its 11900 bytes but when I read it out ir 10090, how is this possible? Thanks
lewax00 17-May-12 10:48am    
Not really sure, but I suggest outputting it into a plain text file and verifying the contents. If content is missing that would probably cause the error (e.g. missing closing tags)
frostcox 17-May-12 15:36pm    
Hi I found the answer, for some strange reason the data wasn't being read out properly when i saved it so I just reversed the process I used for reading the column, I.e file-xmldocument-byte[] and then save, thanks for your help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900