我試圖用FileSavePicker覆蓋UWP中的當前文件。我refered這樣:https://msdn.microsoft.com/zh-cn/windows/uwp/files/quickstart-reading-and-writing-files 但當我使用更短的文件覆蓋一個較長的文件,還有了一個問題:舊文件(長)的額外部分沒有被刪除,就像這樣:如何在UWP中覆蓋文件?
舊文件:
abcdefg
和文件我想保存:
hij
但保存操作後,我得到這個:
hijdefg
我的代碼是在這裏:
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();
}
}
感謝您幫助我!
似乎是一種正常行爲。如果你想用全新的數據覆蓋文件,爲什麼不只是用* ReplaceExisting *選項創建文件而不是打開一箇舊文件? – Romasz
錯誤的方法,你想創建而不是打開。 –