2013-05-01 29 views
0

我有用于从Web服务器下载的图像下面的代码:下载并在窗口中显示的图像8

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:\用户\用户\应用程序数据\本地\套餐\ XXXXX \ LocalState)。

如果我再次运行它,我得到UnauthorizedAccessException was unhandled by user code,Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))CreateFileAsync

任何想法?

+0

可能是其中之一“是它插好”的答案,但你有权限设置正确的文件夹? – AngryDuck 2013-05-01 15:23:02

回答

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

如果你不想下载的图片,你可以这样做:

private void displayImage() 
{ 
    image1.Source = new BitmapImage(
     new Uri("http://www.reignofcomputer.com/imgdump/sample.png")); 
} 

这是否帮助?

+0

sample.png实际上将被替换为动态图像,所以我需要每次都下载一个新的。 – ReignOfComputer 2013-05-01 15:29:58

相关问题