我有以下代码从网络服务器下载图片:
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))
,CreateFileAsync
。
有什么想法吗?
答案 0 :(得分:4)
这是一个应用程序的工作示例,可下载图像并将其显示为应用程序的背景:
http://laurencemoroney.azurewebsites.net/?p=247
async void doLoadBG()
{
System.Xml.Linq.XDocument xmlDoc = XDocument.Load(
"http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US");
IEnumerable<string> strTest = from node in xmlDoc.Descendants("url")
select node.Value;
string strURL = "http://www.bing.com" + strTest.First();
Uri source = new Uri(strURL);
StorageFile destinationFile;
try
{
destinationFile = await ApplicationData.Current.LocalFolder
.CreateFileAsync(
"downloadimage.jpg", CreationCollisionOption.GenerateUniqueName);
}
catch (FileNotFoundException ex)
{
return;
}
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download =
downloader.CreateDownload(source, destinationFile);
await download.StartAsync();
ResponseInformation response = download.GetResponseInformation();
Uri imageUri;
BitmapImage image = null;
if (Uri.TryCreate(destinationFile.Path, UriKind.RelativeOrAbsolute,
out imageUri))
{
image = new BitmapImage(imageUri);
}
imgBrush.ImageSource = image;
}
答案 1 :(得分:1)
如果您不想下载图片,可以这样做:
private void displayImage()
{
image1.Source = new BitmapImage(
new Uri("http://www.reignofcomputer.com/imgdump/sample.png"));
}
这有帮助吗?