如何在UWP中移动和替换另一个文件后修改文件?

时间:2018-03-23 13:25:57

标签: c# file uwp storagefile

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

E.g。在这里,我打开一个文件并将其保存在_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.

1 个答案:

答案 0 :(得分: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 File access permissions