1

Grabbing an image via GetStreamAsync, how do I determine status?

HttpClient OpenClient = new HttpClient();
Stream firstImageStream = OpenClient.GetStreamAsync("imageUrl.jpg").Result;

Sometimes this will give an error (403 or 404 typically) and I simply want to skip processing those results.

All I can find says to use the StatusCode property or IsSuccessStatusCode, but those seem to only work on HttpResponseMessage, which is from GetAsync, which does not give me the Stream I need to process the image.

Randy Hall
  • 7,716
  • 16
  • 73
  • 151
  • There is a reason all of the HttpClient functions are async, if you don't plan on using actually async code you should be using [WebClient](https://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.110).aspx) and using it's non async methods. – Scott Chamberlain Aug 02 '16 at 15:27

1 Answers1

6

The stream doesn't have the response status code. You'll need to get the HttpResponseMessage first, check the status code, and then read in the stream.

HttpClient OpenClient = new HttpClient();
var response = await OpenClient.GetAsync("imageUrl.jpg");
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
    Stream stream = await response.Content.ReadAsStreamAsync();
}
Pharylon
  • 9,796
  • 3
  • 35
  • 59
  • 'System.Threading.Tasks.Task' does not contain a definition for 'Content' and no extension method 'Content' accepting a first argument of type 'System.Threading.Tasks.Task' could be found – Randy Hall Aug 02 '16 at 16:00
  • 1
    You didn't await the task. Check my code above: var response = **await** OpenClient.GetAsync("imageUrl.jpg"); – Pharylon Aug 02 '16 at 18:03
  • `HttpResponseMessage` and `HttpContent` are Disposable classes, why don't you use `using (...)` structure ? – 23W Aug 14 '18 at 09:07
  • And why do not use `IsSuccessStatusCode`? – 23W Aug 14 '18 at 09:15
  • For me solution is working! This inconsistency of API is something what Microsoft should change. – hsd Sep 29 '20 at 20:12
  • 1
    I'm going to add a comment to this old answer because I got burned by this recently: If you use something similar to the code in this answer, make sure you pass `HttpCompletionOption.ResponseHeadersRead` to `GetAsync`. Otherwise you'll end up reading the whole file into memory even if the status code is something else than 200. This article has more information: https://medium.com/@szntb/getting-burnt-with-httpclient-9c1712151039 – Magnus Grindal Bakken Nov 09 '22 at 15:26