删除以前在WinRT中的DataTemplate中使用的图像文件时拒绝访问

Kin*_*ing 5 xaml datatemplate windows-runtime winrt-xaml storagefile

我有我的GridView使用的图像(PNG)文件作为其DataTemplate的一部分.如果我尝试删除GridView中的特定对象行,我也会删除该行的相关图像文件.列表中的每个项目的图像都不同.

我正在使用此代码删除图像文件

StorageFile _file = await DataStore.GetFileAsync(filename);
await _file.DeleteAsync(StorageDeleteOption.Default);
Run Code Online (Sandbox Code Playgroud)

图像文件在GridView的DataTemplate下的GridView上呈现.所以在我的List中的每个对象模型中,我都有一个公共属性,它为我的DataTemplate返回一个ImageSource.

我正在从List中删除对象行并在GridView刷新新的List项之后立即调用我的删除过程.

即使列表不再包含对象(使用图像),如果我尝试删除文件,应用程序也会抛出Access is Denied异常.当应用程序运行时,如果我尝试手动删除该特定文件(通过文件浏览器),它也不允许我.

我尝试清除我的应用程序中的所有未使用的对象,甚至在删除图像之前将GridView的ItemSource设置为null并将List设置为null.仍有例外情况仍然存在.

提前致谢.

小智 0

技巧是使用 Uri 对象加载图像(而不是字符串文件名),然后使用完全相同的 Uri 实例删除文件(当然,在从 UI 中删除图像之后)。这是一个例子:

//Save the Uri as a member variable so you can get to it later
private Uri uri;

//Create the Uri
uri = new Uri(OriginalImageFilename, UriKind.Absolute);

//Load the image
BitmapImage bitmapImage = new BitmapImage(uri);
//This can also be done by binding a Image control's source property to the uri.

//Delete the image (remember to use the same Uri instance)
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);
await file.DeleteAsync();
Run Code Online (Sandbox Code Playgroud)