Share via

How can I read the file contents using http synchronously

David Thielen 3,226 Reputation points
2023-09-16T17:37:58.9733333+00:00

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);
    }
}

Developer technologies | ASP.NET | ASP.NET Core
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 83,421 Reputation points Volunteer Moderator
    2023-09-16T19:29:08.3133333+00:00

    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.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.