无法使用wpf中的c#从具有身份验证的服务器下载图像
本文关键字:身份验证 服务器 图像 下载 wpf 中的 | 更新日期: 2023-09-27 18:27:16
am使用以下代码从服务器下载图像,但失败了。我正在使用服务器身份验证,请帮助
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;
}
}
}
问题是在图像完全下载之前关闭响应流。为了确保它被完全下载,您可以将它复制到中间的MemoryStream中。此外,如果要在EndInit
之后立即关闭流,则必须设置BitmapCacheOption.OnLoad
标志。请参阅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为类似的目的提供了DownloadCompleted
和DownloadFailed
事件处理程序。请注意,关闭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;