5

I'm trying to download from a specific URL using this code:

var requestUri = "https://github.com/gus33000/MSM8994-8992-NT-ARM64-Drivers/archive/master.zip";

using (var client = new HttpClient())
{
    using (var response = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead))
    {
        var contentLength = response.Content.Headers.ContentLength;
    }
}

If you run the code, you will likely get null in contentLength. But, why? Sometimes, the length is returned. What should I do to retrieve the length of the file always?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
SuperJMN
  • 13,110
  • 16
  • 86
  • 185
  • Probably nothing. Just download, independent of the returned length. – Uwe Keim Mar 07 '19 at 10:07
  • The problem is that the file is really big. I'm using progress reporting to give the user feedback about the % completed. Having no total size is a true problem :( – SuperJMN Mar 07 '19 at 10:09
  • 1
    It depends on the server you download files from. If they set the header, you can use it. If they don't... You can't – Deblaton Jean-Philippe Mar 07 '19 at 10:12
  • You are probably exceeding the time out. – jdweng Mar 07 '19 at 10:39
  • Firefox doesn't know either. The headers are simply not set. In these cases, I usually do what the WebBrowsers do: show a marquee and the download progression in bytes. Something to look at. With a `Cancel` button nearby. – Jimi Mar 07 '19 at 10:49
  • @jdweng `HttpCompletionOption.ResponseHeadersRead`. This request returns almost immediately. – Jimi Mar 07 '19 at 10:50
  • Are you getting a status back 200 or something else when it fails? – jdweng Mar 07 '19 at 11:29
  • @jdweng the download is OK, and the headers are returned right away, but most of times (90% of times) the Content Length comes empty. – SuperJMN Mar 07 '19 at 11:45
  • I usually consider random when it works most of the time and occasionally fails. Use a sniffer like wireshark or fiddler and see if issue is the response from the server or the c# code. Check if you are using http 1.0 (stream mode) or http 1.1 (chunk mode). And the status returned. Without knowing the status it is hard to give a good answer. – jdweng Mar 07 '19 at 14:46
  • @SuperJMN - Did you find solution for this problem, I am facing exactly same problem only that for me it fails once in every 10 minutes. – Ravi A. Aug 10 '19 at 16:35
  • I've found that server like the ones that GitHub uses to host content, usually don't report the content-lenght, so you need to be ready to make the download mechanism fail-proof. Please, refer to my Downloader class to see how I overcome the issue: https://github.com/SuperJMN-Zafiro/Zafiro/blob/master/Source/Zafiro.Core/Downloader.cs – SuperJMN Jul 19 '20 at 22:28

0 Answers0