0

我有以下代码用于从网络服务器下载图像:

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

有任何想法吗?

4

2 回答 2

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;
}
于 2013-05-01T15:29:02.867 回答
1

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

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

这有帮助吗?

于 2013-05-01T15:21:09.577 回答