2013-05-01 61 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