OpenStreamForWriteAsync会留下额外的字节

时间:2016-03-13 02:01:10

标签: c# win-universal-app

我的情况是我的文件更改大小(经常添加和删除的内容)。用户可以选择保存文件。但是,如果他们将文件保存在一个较大的现有文件(允许他们这样做)上,那么它会通过在较大文件的末尾留下额外的文件来扰乱文件。

例如,我有以下代码:

        // The user saves their data to disk. No problem.
        FileSavePicker savePicker = new FileSavePicker();
        savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
        savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
        savePicker.SuggestedFileName = "New Document";

        StorageFile file = await savePicker.PickSaveFileAsync();
        if (file != null)
        {
            using (var stream = await file.OpenStreamForWriteAsync())
            {
                using (var sw = new StreamWriter(stream))
                {
                    sw.Write("ABCDEFGH");
                }
            }
        }

        // The user saves their data to disk again, overwriting their first file.
        FileSavePicker savePicker2 = new FileSavePicker();
        savePicker2.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
        savePicker2.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
        savePicker2.SuggestedFileName = "New Document";

        StorageFile file2 = await savePicker2.PickSaveFileAsync();
        if (file2 != null)
        {
            using (var stream = await file2.OpenStreamForWriteAsync())
            {
                using (var sw = new StreamWriter(stream))
                {
                    sw.Write("1234");
                }
            }
        }
    }

当这段代码完成后,我得到的文件是1234EFGH,而不是1234,正如我所料。

我做错了什么?我无法在两次调用之间删除文件,否则StorageFile将在OpenStreamAForWriteAsync(...)

上崩溃

1 个答案:

答案 0 :(得分:1)

如果覆盖现有文件,则剪切流的尾部调整流的长度以匹配最后位置(确保在更新长度之前刷新流/写入器):

     stream.SetLength(stream.Position);