Search code examples
windows-runtimexml-serializationstoragefile

Writing a shorter stream to a StorageFile


I have a StorageFile that contains XML. I read the XML from the StorageFile, then I edit it and then I save it again to the StorageFile using the following code:

using (var writeStream = await storageFile.OpenStreamForWriteAsync())
{
    xDocument.Save(writeStream, SaveOptions.None);
}

However, when I make the contents shorter, eg from

<Node>
    <Child>This is a verrrrrryyy long text</Child>
<Node>

to

<Node>
    <Child>This is short</Child>
<Node>

The result on disk is as follows:

<Node>
    <Child>This is short</Child>
<Node>rrryyy long text</Child>
<Node>

Obviously the Stream writes only the the new bytes in the file, leaving the old ones intact thus resulting in an invalid XML the next time I try to open it, so this is probably not the right way to save...

How should I be saving it?


Solution

  • SOLUTION is to truncate the stream:

    using (var writeStream = await f.OpenStreamForWriteAsync()) 
    { 
       if (writeStream.CanSeek && writeStream.Length > 0) 
          writeStream.SetLength(0); 
       _xml.Save(writeStream, SaveOptions.None); 
    }