Search code examples
c#xmllinquwpwindows-store

Saving an xml file using stream results in a duplicate root elements


So I'm attempting to open an xml file, add an XElement to the root element, and save it. Except my C# Code:

StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("UserPinouts.tpack", CreationCollisionOption.OpenIfExists);

using (var stream = await file.OpenStreamForWriteAsync())
{
    XDocument doc = XDocument.Load(stream);
    doc.Root.Add(new XElement(XElement.Parse(CurrentPinOut)));
    doc.Save(stream);

    Debug.WriteLine(doc.ToString());
    stream.Flush();
}

Gives me the following xml file:

<?xml version="1.0" encoding="utf-8" ?>
<RootElement>
    <XElement1/>
</RootElement>

<?xml version="1.0" encoding="utf-8" ?>
<RootElement>
    <XElement1/>
    <XElement2/>
</RootElement>

Instead of just that second part. I've tried changing the way I add the XElement, but I get this everytime, so I'm guessing it must be a problem with the way I open/close the stream. How could I fix this?


Solution

  • Try to reset stream position to the beginning, just before calling Save() method :

    stream.Position = 0;
    doc.Save(stream);
    

    I have seen this solved similar problem in old Windows Phone questions. These are some of them : 1. Appending new XElement adds an entire XML to existing xml in stream, 2. updating an existing xml file in Windows Phone