Update - The "Access Denied" errors are being caused by multiple things.
The first cause has to do with the downloading of the image. It appears something in download code is holding open the file. I have simplified the download code below.
The second cause has to do with the BitmapImage
object holding open the file. See this post for more info: Access Denied when deleting image file previously used in DataTemplate in WinRT
One way around the second issue is to use a stream
instead of a Uri
to initialize the BitmapImage
.
Here is a version that works for me (your original code is also here, but commented out):
var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
"test.png", CreationCollisionOption.ReplaceExisting);
/*
var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);
DataWriter writer = new DataWriter(fs.GetOutputStreamAt(0));
writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
await writer.StoreAsync();
writer.DetachStream();
await fs.FlushAsync();
writer.Dispose();
if (Uri.TryCreate(imageFile.Path, UriKind.RelativeOrAbsolute, out imageUri))
{
image = new BitmapImage(imageUri);
}
*/
var fs = await imageFile.OpenStreamForWriteAsync();
await response.Content.CopyToAsync(fs);
await fs.FlushAsync();
// you may want to have this Dispose as part of a
// finally block (try/ catch/ finally)
fs.Dispose();
var bs = await imageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
image = new BitmapImage();
image.SetSource(bs);
...
image1.Source = image;