Reputation: 441
I am using the GetStreamAsync-Method in order to read in a file through a stream. But I am wondering: What happens if the URL provided is currently not available? How would I know if GetStreamAsync failed?
Here is the code I am working with:
var tmpMyDataFile = Path.GetTempFileName();
using (var myDataStream = await _httpClient.GetStreamAsync(MyURL))
{
using (var tmpMyDataStream = File.OpenWrite(tmpMyDataFile))
{
await myDataStream.CopyToAsync(tmpMyDataStream);
}
}
Do I have to do this through catching the HttpRequestException exception or is there some sort of StatusCode I could retrieve somehow? If I have to do this via exception catching, what exactly is the meaning of the TaskCanceledException described in the doc here: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.getstreamasync?view=net-5.0
TaskCanceledException: The request failed due to timeout. <- Which timeout?
Upvotes: 1
Views: 1050
Reputation: 456417
What happens if the URL provided is currently not available? How would I know if GetStreamAsync failed?
As documented, you'll get an HttpRequestException
. You can check the status code (if any) using its StatusCode
property.
Do I have to do this through catching the HttpRequestException exception or is there some sort of StatusCode I could retrieve somehow?
If you want to avoid the exception, then you should use SendAsync
, which returns an HttpResponseMessage
with a StatusCode
. Note that SendAsync
will still throw an exception if it is unable to get any response at all.
If I have to do this via exception catching, what exactly is the meaning of the TaskCanceledException
Only on .NET Core and .NET 5+ only, TaskCanceledException
indicates a timeout. By default, HttpClient.Timeout
is set to 100 seconds. If you need to handle timeout exceptions, I recommend catching OperationCanceledException
rather than TaskCanceledException
.
Upvotes: 2