I am uploading files with a progress bar. I am using IAsyncOperationWithProgress for this problem, specifically this code . This works well, but I only get the number of bytes that were received / loaded. But I need to calculate the percentage to display progress. This means that I need to know the total number of bytes at the beginning of the download, and I have not found a way to do this efficiently.
The following code enables progress reports. I tried to get the length of the stream using responseStream.Length , but with the error "This stream does not support search operations." was cast.
static async Task<byte[]> GetByteArratTaskProvider(Task<HttpResponseMessage> httpOperation, CancellationToken token, IProgress<int> progressCallback)
{
int offset = 0;
int streamLength = 0;
var result = new List<byte>();
var responseBuffer = new byte[500];
var httpInitialResponse = await httpOperation;
using (var responseStream = await httpInitialResponse.Content.ReadAsStreamAsync())
{
int read;
do
{
if (token.IsCancellationRequested)
{
token.ThrowIfCancellationRequested();
}
read = await responseStream.ReadAsync(responseBuffer, 0, responseBuffer.Length);
result.AddRange(responseBuffer);
offset += read;
progressCallback.Report(offset);
} while (read != 0);
}
return result.ToArray();
}
, ? - HttpClient? BackgroundDownloader, . .