我有以下代码用于从网络服务器下载图像:
private async void Test_Click(object sender, RoutedEventArgs e)
{
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(
HttpMethod.Get, "http://www.reignofcomputer.com/imgdump/sample.png");
HttpResponseMessage response = await httpClient.SendAsync(request,
HttpCompletionOption.ResponseHeadersRead);
var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
"sample.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();
displayImage();
}
private void displayImage()
{
image1.Source = new BitmapImage(
new Uri("ms-appdata:///local/sample.png", UriKind.Absolute));
}
当我运行代码时,尽管图像出现在文件夹中(位于C:\Users\User\AppData\Local\Packages\XXXXX\LocalState),但图像无法显示。
如果我再次运行它,我会得到一个UnauthorizedAccessException was unhandled by user code
, Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at CreateFileAsync
。
有任何想法吗?