1

在 UWP 中调用MoveAndReplaceAsync用新文件替换旧文件后,我无法修改新文件。

例如,在这里我打开一个文件并将其保存在_file

private async void OpenButton_Click(object sender, RoutedEventArgs e)
    {
        var picker =
            new Windows.Storage.Pickers.FileOpenPicker
            {
                ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail,
                SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary
            };
        picker.FileTypeFilter.Add(".txt");

        _file = await picker.PickSingleFileAsync();
    }

在此处理程序中,我将其写入一个新文件,将其移动并替换为打开的文件,然后尝试追加。

    private async void MoveAndReplaceAndAppend_Click(object sender, RoutedEventArgs e)
    {
        // Create a temp file for writing to
        var tempFolder = ApplicationData.Current.TemporaryFolder;
        var filename = Guid.NewGuid().ToString();
        var tmpFile = await tempFolder.CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName);

        try
        {
            var stream = await tmpFile.OpenAsync(FileAccessMode.ReadWrite);
            var dw = new DataWriter(stream);
            dw.WriteString("New file");
            await tmpFile.MoveAndReplaceAsync(_file);
        }
        catch (Exception ex)
        {
            var dlg = new MessageDialog($"Error while move and replacing {ex.Message}");
            await dlg.ShowAsync();
        }

        var failures = "";
        try
        {
            await FileIO.AppendTextAsync(_file, "testing");
        }
        catch (Exception ex)
        {
            failures += $"Failed appending to _file: {ex.Message}\n";
        }

        try
        {
            await FileIO.AppendTextAsync(tmpFile, "testing");
        }
        catch (Exception ex)
        {
            failures += $"Failed appending to tmpFile: {ex.Message}\n";
        }

        var errorDialog = new MessageDialog($"Error while appending\n{failures}");
        await errorDialog.ShowAsync();
    }

我试过附加旧的和新的StorageFile,但总是得到以下错误。

Failed appending to _file: The process cannot access the file because it is being used by another process.

Failed appending to tmpFile: The process cannot access the file because it is being used by another process.
4

1 回答 1

1

问题是前一个流的生命周期在替换操作之前没有结束。您可以使用Dispose()手动管理输出流的生命周期。

var stream = await tmpFile.OpenAsync(FileAccessMode.ReadWrite);
var dw = new DataWriter(stream);
dw.WriteString("New file");
stream.Dispose();

为什么它们超出范围时不自动关闭?

不必手动管理输出流的生命周期。您还可以使用using语句来管理流的生命周期。

using (var stream = await tmpFile.OpenAsync(FileAccessMode.ReadWrite))
{
    var dw = new DataWriter(stream);
    dw.WriteString("New file");
}

using当执行离开语句时,流将自动释放。有关更多信息,您可以参考UWP 文件访问权限

于 2018-03-26T03:01:44.507 回答