How to check the size of HTTP resource in C#

By FoxLearn 11/10/2024 2:51:35 AM   93
You can check the size of an HTTP resource in C# by sending a HEAD request and inspecting the Content-Length header.

Sometimes, it's useful to know the size of an HTTP resource before downloading it, such as checking the size of a video file before starting the download. The HTTP HEAD method is ideal for this purpose. Unlike the GET method, which retrieves both the headers and the actual data, the HEAD method only fetches the headers, including metadata like Content-Length, without transferring the resource itself.

How to get the size of image file with HEAD in C#?

To get the size of an image file using the HTTP HEAD method in C#, you can use the HttpClient class to send a HEAD request to the URL of the image and then inspect the Content-Length header in the response.

using (var client = new HttpClient())
{
    var request = new HttpRequestMessage(HttpMethod.Head, "https://example.com/path/to/image.jpg");
    var response = await client.SendAsync(request);
    if (response.IsSuccessStatusCode)
    {
        var contentLength = response.Content.Headers.ContentLength;
        Console.WriteLine($"Content-Length: {contentLength} bytes");
    }
}

First, We will create a HEAD request to the provided URL, then send the HEAD request asynchronously and retrieves the response.

Finally, Use response.Content.Headers.ContentLength to access the Content-Length header from the HTTP response, which contains the size of the resource in bytes.