Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I overwrite a file in UWP?

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!

like image 902
huangbiubiu Avatar asked Feb 07 '23 13:02

huangbiubiu


1 Answers

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();                        
}
like image 167
Tim Greenfield Avatar answered Feb 16 '23 02:02

Tim Greenfield