0

I'm trying to download a GitHub repository and want to see the progress on the downloaded bytes. This is my code so far:

Task<byte[]> task;
long lastTime = 0;
byte[] contents;

using (var client = new System.Net.Http.HttpClient())
{
    var credentials = string.Format(System.Globalization.CultureInfo.InvariantCulture,
        "{0}:", githubToken);
    credentials = Convert.ToBase64String(System.Text.Encoding.ASCII
        .GetBytes(credentials));
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers
        .AuthenticationHeaderValue("Basic", credentials);
    task = client.GetByteArrayAsync(url);
    task.ConfigureAwait(false);

    while(!task.IsCompleted)
    {
        if (task.IsFaulted || task.IsCanceled)
            break;
        else if(timer.ElapsedMilliseconds - (double)lastTime > 0.2)
        {
            Console.Clear();
            Console.WriteLine();// task.Result.Length or something
            lastTime = timer.ElapsedMilliseconds;
        }
    }

    contents = task.Result;
}

The problem is I can't just call task.Result.Length as it would, obviously, halt to await the task completion. GetByteArrayAsync is also not 'awaitable'. I couldn't find anything so now I was wondering if it is even possible?

Thanks in advance

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
  • 1
    *I couldn't find anything* ... good one ... what about all the results for "C# HttpClient with progress" (of course it will not work if server sends chunked content (content-lenght: -1) – Selvin Nov 16 '22 at 12:18
  • @Selvin yea sorry I was so focused on the task I didn't look out for the HttpClient – Kay Steinhoff Nov 16 '22 at 12:23
  • also you can check the following link or how to report state from async tasks https://blog.stephencleary.com/2012/02/reporting-progress-from-async-tasks.html – DonMiguelSanchez Nov 16 '22 at 12:29
  • Does this answer your question? [Progress bar with HttpClient](https://stackoverflow.com/questions/20661652/progress-bar-with-httpclient) – Chris Schaller Nov 16 '22 at 12:30
  • Try this older solution: https://stackoverflow.com/a/46497896/1690217 Ultimately you have to read the response as a stream to access progress information. So stream the bytes and receive using a stream reader. – Chris Schaller Nov 16 '22 at 12:33

0 Answers0