I tried to overwrite a current file in UWP using FileSavePicker. I refered to this: https://msdn.microsoft.com/zh-cn/windows/uwp/files/quickstart-reading-and-writing-files But when I use a shorter file to overwrite a longer file, there comes a problem: the extra part of the old file(longer) isn't deleted, like this:
The old file:
abcdefg
And the file I want to save:
hij
But after saving operations, I get this:
hijdefg
My code is here:
private async void Save_Click(object sender, RoutedEventArgs e)
{
XmlDocument Line = SaveToXml();
//Save it
FileSavePicker fileSaving = new FileSavePicker();
fileSaving.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
fileSaving.SuggestedFileName = "NewLine";
fileSaving.FileTypeChoices.Add("Simple Line Files", new List<string>() { ".Line" });
StorageFile file = await fileSaving.PickSaveFileAsync();
if (file != null)
{
CachedFileManager.DeferUpdates(file);
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
//var stream = await file.OpenStreamForWriteAsync();
using (var outputStream = stream.GetOutputStreamAt(0))
{
using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
{
string xmlDoc = Line.OuterXml;
Debug.WriteLine(Line.OuterXml);
dataWriter.WriteString(xmlDoc);
await dataWriter.StoreAsync();
await outputStream.FlushAsync();
}
}
stream.Dispose();
}
}
Thanks for helping me!
You can also call Stream.SetLength(0)
immediately after opening the stream to clear it before you start writing.
var streamToWrite = await file.OpenStreamForWriteAsync().ConfigureAwait(false);
streamToWrite.SetLength(0);
using (var streamWriter = new StreamWriter(streamToWrite))
{
streamWriter.Write(data);
streamWriter.Flush();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With