How can I read the file contents using http synchronously

David Thielen 1,406 Reputation points

In an event that is called synchronously, so I can't use await (so no IHttpClientFactory), what is the correct way to read the contents of a file.

I am using the following, and it works. But the compiler is telling me I should not use WebClient.

And to repeat, I have no choice in the matter - this cannot be an async method.

public byte[]? GetContent(IBlobService blobService, string blobUrl)
    using (var client = new WebClient())
        return client.DownloadData(blobUrl);

A set of technologies in the .NET Framework for building web applications and XML web services.
3,546 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce ( 43,906 Reputation points

    why can't you use IHttpClientFactory? You can make the HttpClient async call sync with .GetAwaiter().GetResult().

    var buffer = httpClient.GetByteArrayAsync(blobUrl).GetAwaiter().GetResult();
    1 person found this answer helpful.