我想从网站下载图像.我正在使用的代码在图像可用时工作正常.如果图像不可用则会产生问题.如何验证图像的可用性?
码:
方法1:
WebRequest requestPic = WebRequest.Create(imageUrl);
WebResponse responsePic = requestPic.GetResponse();
Image webImage = Image.FromStream(responsePic.GetResponseStream()); // Error
webImage.Save("D:\\Images\\Book\\" + fileName + ".jpg");
Run Code Online (Sandbox Code Playgroud)
方法2:
WebClient client = new WebClient();
Stream stream = client.OpenRead(imageUrl);
bitmap = new Bitmap(stream); // Error : Parameter is not valid.
stream.Flush();
stream.Close();
client.dispose();
if (bitmap != null)
{
bitmap.Save("D:\\Images\\" + fileName + ".jpg");
}
Run Code Online (Sandbox Code Playgroud)
编辑:
Stream有以下声明:
Length '((System.Net.ConnectStream)(str)).Length' threw an exception of type 'System.NotSupportedException' long {System.NotSupportedException}
Position '((System.Net.ConnectStream)(str)).Position' threw an exception of type 'System.NotSupportedException' long {System.NotSupportedException}
ReadTimeout …Run Code Online (Sandbox Code Playgroud)