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
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.