0

我正在使用以下代码从服务器下载图像但失败。我正在使用服务器身份验证,请帮忙

  private BitmapImage getimage (string uri)
    {


        var webRequest = WebRequest.Create(uri);//making a variable webrequest,
        webRequest.Credentials = new NetworkCredential("user", "password");//credential is using for authentication
        using (var webResponse = webRequest.GetResponse())//use for stucking problem of button
        {
            using (var responseStream = webResponse.GetResponseStream())
            {
                BitmapImage img = new BitmapImage();
                img.BeginInit();
                img.StreamSource = responseStream;
                img.EndInit();
                return img;

            }
        }


    }
4

1 回答 1

1

问题是您在图像完全下载之前关闭了响应流。为了确保完全下载,可以将其复制到一个中间的 MemoryStream 中。BitmapCacheOption.OnLoad此外,如果您想在之后立即关闭流,则必须设置标志EndInit请参阅BitmapImage.StreamSource中的备注部分。

using (var webResponse = webRequest.GetResponse())
using (var responseStream = webResponse.GetResponseStream())
using (var memoryStream = new MemoryStream())
{
    responseStream.CopyTo(memoryStream);
    BitmapImage img = new BitmapImage();
    img.BeginInit();
    img.CacheOption = BitmapCacheOption.OnLoad;
    img.StreamSource = memoryStream;
    img.EndInit();
    return img;
}

或者,您可以延迟关闭 WebResponse,直到图像完全下载。BitmapImage 为此类目的提供了DownloadCompletedDownloadFailed事件处理程序。请注意,关闭 WebResponse 也会关闭响应流。

var webResponse = webRequest.GetResponse();
var img = new BitmapImage();
img.DownloadCompleted += (o, e) => webResponse.Close();
img.DownloadFailed += (o, e) => webResponse.Close();
img.BeginInit();
img.StreamSource = webResponse.GetResponseStream();
img.EndInit();
return img;
于 2013-08-09T17:07:53.060 回答