首页 > 解决方案 > CopyAsync 方法不替换现有文件。UWP。应用存储

问题描述

现在我正在我的应用程序中进行编辑操作。因此,在编辑操作中,可以更改图像,同时保留联系人图像的文件的名称不能重命名(在操作的一个会话期间,图像文件将发生变化,但所有这些文件都将采用相同的名称) .

而且我使用了方法重载(此处CopyAsync为该方法的文档),据我所知,必须将文件替换为具有相同名称的现有文件。

我得到imageFile变量FileOpenPicker。每次我选择 image by 时,下面的代码都会运行FileOpenPickerImage当我在结果UI 控件中重新选择图像时,会显示我之前选择的图像。我希望这Image将查看我选择的最后一张图片,但这并没有发生。

    public BitmapImage Image { set; get; }

    //Copy of the file that saved in temporary storage
    StorageFile fileForView = await imageFile.CopyAsync 
       (ApplicationData.Current.TemporaryFolder,
       fileName,
       NameCollisionOption.ReplaceExisting);

    Image = new BitmapImage(new Uri(fileForView.Path));

CopyAsync如果我在这种情况下,也许我不正确地理解方法的逻辑,如果可能的话,请告诉我如何使我的计划使用这种方法。否则,请提供您的解决方案,因为我现在不知道该怎么做。

我也尝试用CopyAndReplaceAsync方法来做到这一点。但还是没有结果。我这样做:

         if (null != await ApplicationData.Current.TemporaryFolder.TryGetItemAsync(fileName))
        {
            StorageFile storageFile = await ApplicationData.Current.TemporaryFolder.GetFileAsync(fileName);

            await storageFile.CopyAndReplaceAsync(imageFile);
        }

标签: c#uwp

解决方案


我希望 Image 会查看我选择的最后一张图片,但这并没有发生。

上面的CopyAsync方法是正确的,我用下面的代码测试过,效果很好。

private async void ListOption_ItemClick(object sender, ItemClickEventArgs e)
{
    FileOpenPicker openPicker = new FileOpenPicker();
    openPicker.ViewMode = PickerViewMode.Thumbnail;
    openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
    openPicker.FileTypeFilter.Add(".jpg");
    openPicker.FileTypeFilter.Add(".jpeg");
    openPicker.FileTypeFilter.Add(".png");

    StorageFile file = await openPicker.PickSingleFileAsync();
    if (file != null)
    {
        StorageFile fileForView = await file.CopyAsync(ApplicationData.Current.TemporaryFolder, file.Name, NameCollisionOption.ReplaceExisting);
        Image = new BitmapImage(new Uri(fileForView.Path));
        TestImg.Source = Image;
    }
    else
    {

    }
}

推荐阅读