2

I want to get the file size before I download it, In my code I'm extracting the Content-Length header from the request. My code works fine for a lot of cases, but in some cases there is no Content-Length header, my question is how can I get the file size in cases I dont have Content-Length header, here my code:

HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.learningcontainer.com/wp-content/uploads/2019/09/sample-docx-file-for-testing.docx");
using (HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse())
{
var headers = myHttpWebResponse.Headers;
    if (headers.AllKeys.Contains("Content-Length"))
        var fileSize = headers.GetValues("Content-Length")[0];
    else
    {
     //code here should be added
    }
}

For example in the given url there is no Content-Length header

spez
  • 409
  • 8
  • 21
  • 3
    There's no way to find out the size if the server doesn't send the `Content-Length` header, since the content is going to be streamed; you can't know the stream size without actually reading through it. – Emanuel Vintilă Mar 04 '20 at 06:22

2 Answers2

0

You won't know the size of the content in advance without a Content-Length header.

If you can't control the server then you're going to have to handle it. One option would be to stream the data into a temporary file on disk, and once you have that, you can determine the size, and pass it on to the next step in whatever you're doing.

You could stream it into a memory buffer but since you don't how big it will be, there's the risk that you'll end up running out of memory.

stevex
  • 5,589
  • 37
  • 52
0

this is problery gonna sound insane but if the http server supports range as a header tag, and you are able to get at range exceed exception then you can make a guessing game, starting with som big values then decreasing. please do not make too many request or the owner of the webserver is going to be unhappy.

Jim HD
  • 1