i have the following code:
var request = (HttpWebRequest)HttpWebRequest.Create(url);
var response = request.GetResponse();
var stream = response.GetResponseStream();
if (stream != null) {
Image newImage = Image.FromStream(stream, true);
pic.Thumb = newImage.ImageToByteArray();
}
What happens if the read times out? Or the connection is aborted mid-download?
The docs say that it will throw an ArgumentException if it’s not a valid format or is null, but I have no idea if it will throw that exception if the image is only partially downloaded.
Unfortunately, I can’t rely on the ContentLength header to tell me the proper size of the file, because the server lies and gives a larger content length than the file actually is. So my hope is that Image.FromStream will be able to tell if the image is complete or not.
Can anyone provide some insight here?
Note: ImageToByteArray is just an extension method that uses a memory stream to convert the Image to a byte[]
UPDATE:
According to Darin, then an ExternalException gets thrown when you try to save the image. However, my own testing in which I truncated an image file shows that FromStream does in fact throw an ArgumentException if the image is not the correct number of bytes.
An exception will be thrown before entering the
ifcondition.An exception will be thrown before entering the
ifcondition.An image cannot be partially downloaded. The
GetResponseStreamis a blocking method meaning that either you get everything, or an exception (or of course in your case you could also get an exception if what you fetched is not an image but some HTML page which will happen when you try to instantiate the Image GDI+ object).As a side note, to avoid leaking, you probably also want to wrap this
Imagedisposable resource into ausingstatement.