How to check the size of HTTP resource in C#
By FoxLearn 11/10/2024 2:51:35 AM 93
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 set Filter Criteria with multi conditions in C#?
- How to get application folder path in C#
- How to copy data to clipboard in C#
- How to mark a method as obsolete or deprecated in C#
- How to Call the Base Constructor in C#
- Deep Copy of Object in C#
- How to Catch Multiple Exceptions in C#
- How to cast int to enum in C#