How to check the size of HTTP resource in C#
By FoxLearn 11/10/2024 2:51:35 AM 131
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.
- How to handle nulls with SqlDataReader in C#
- Resolve nullable warnings
- Cannot convert null to type parameter ‘T’
- How to create a custom exception in C#
- How to check if a nullable bool is true in C#
- How to make a file read-only in C#
- How to Get all files in a folder in C#
- How to validate an IP address in C#