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 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); 
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top