How to check the size of HTTP resource in C#

By FoxLearn 12/27/2024 2:14:03 AM   128
The HTTP HEAD command is useful when we want to know the size of a resource, like a video or an image, before downloading it.

Unlike the HTTP GET command, which retrieves the resource along with its data, the HEAD command only retrieves the header metadata without sending the actual content. This allows us to check details such as the file size of an image or other resources before initiating a full download.

For example:

string url = "https://foxlearn.com/images/system-tray-e2775712-a269-473b.png";
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "HEAD";
 
var resp = req.GetResponse();
string strLength = resp.Headers.Get("Content-Length");
resp.Close();
 
int size = int.Parse(strLength);
Console.WriteLine(size);

You can also use HttpClient instead of HttpWebRequest: HttpClient is the modern, more flexible, and preferred way to handle HTTP requests in .NET. It can also be reused across multiple requests and supports asynchronous operations for better performance.

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string url = "https://foxlearn.com/images/system-tray-e2775712-a269-473b.png";

        try
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "*/*");
                
                // Send a HEAD request to get only headers
                HttpResponseMessage response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, url));
                
                if (response.IsSuccessStatusCode)
                {
                    if (response.Content.Headers.ContentLength.HasValue)
                    {
                        long size = response.Content.Headers.ContentLength.Value;
                        Console.WriteLine(size);
                    }
                    else
                    {
                        Console.WriteLine("Content-Length header is not available.");
                    }
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}