在 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.