0

i write some UWP app. There i want to save/Update/Delete in a XML List. My XML List Looks like:

<?xml version="1.0" encoding="utf-8"?>
<rootnode>
    <Kunde Name="Testkunde" />
    <Kunde Name="Testkunde2" />
</rootnode>

If i want to remove a item with this code

StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(@"C:\Users\IT\source\repos\App3\App3");
StorageFile file = await folder.GetFileAsync("Kundenliste.xml");

using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
    Stream s = writeStream.AsStreamForWrite();
    XDocument doc = XDocument.Load(s);

    var q = from node in doc.Descendants("Kunde")
        let attr = node.Attribute("Name")
        where attr != null && attr.Value == "Testkunde"
        select node;

    q.ToList().ForEach(x => x.Remove());
    doc.Save(s);
}

This happens

<?xml version="1.0" encoding="utf-8"?>
<rootnode>
    <Kunde Name="Testkunde" />
  <Kunde Name="Testkunde2"  />
</rootnode><?xml version="1.0" encoding="utf-8"?>
<rootnode>
  <Kunde Name="Testkunde2" />
</rootnode>

anyone can help me?

Hubii
  • 348
  • 1
  • 14
  • 1
    Before writing the `doc`, you need to rewind the `Stream` and clear its contents, e.g. by doing `s.Position = 0; s.SetLength(0)`. See e.g. [FileMode.Open and FileMode.OpenOrCreate difference when file exists? c# bug?](https://stackoverflow.com/q/29799265) for a similar bug in regular .Net. I'm not sure whether the stream returned by `IRandomAccessStream.AsStreamForWrite();` can be repositioned and truncated though. – dbc Mar 16 '18 at 18:07
  • Or, for safety, you might write to a separate file and then do [`MoveAndReplaceAsync(Windows.Storage.IStorageFile)`](https://github.com/MicrosoftDocs/winrt-api/blob/docs/windows.storage/storagefile_moveandreplaceasync_1870118889.md). – dbc Mar 16 '18 at 18:10

1 Answers1

0

Just set

s.Position = 0;
s.SetLength(0);

after

Stream s = writeStream.AsStreamForWrite();
XDocument doc = XDocument.Load(s);

and it will works

Maddin
  • 52
  • 9