How to check the size of HTTP resource in C#
By FoxLearn 11/10/2024 2:51:35 AM 19
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 get project file path in C#
- How to get the current working folder in C#
- How to retrieve the Executable Path in C#
- Server.MapPath in C#
- How to retrieve the Downloads Directory Path in C#
- How to get connection string from app.config in C#
- How to capture image from webcam in C#
- How to restart program in C#