Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Size of Image File before downloading from web

Tags:

c#

.net

I am downloading image files from web using the following code in my Console Application.

WebClient client = new WebClient();
client.DownloadFile(string address_of_image_file,string filename);

The code is running absolutely fine.

I want to know if there is a way i can get the size of this image file before I download it.

PS- Actually I have written code to make a crawler which moves around the site downloading image files. So I doesn't know its size beforehand. All I have is the complete path of file which has been extracted from the source of webpage.

like image 584
user1589754 Avatar asked Aug 22 '12 19:08

user1589754


4 Answers

Here is a simple example you can try if you have files of different extensions like .GIF, .JPG, etc you can create a variable or wrap the code within a Switch Case Statement

System.Net.WebClient client = new System.Net.WebClient();
client.OpenRead("http://someURL.com/Images/MyImage.jpg");
Int64 bytes_total= Convert.ToInt64(client.ResponseHeaders["Content-Length"])
MessageBox.Show(bytes_total.ToString() + " Bytes");
like image 149
MethodMan Avatar answered Nov 20 '22 05:11

MethodMan


If the web-service gives you a Content-Length HTTP header then it will be the image file size. However, if the web-service wants to "stream" data to you (using Chunk encoding), then you won't know until the whole file is downloaded.

like image 35
EthanB Avatar answered Nov 20 '22 06:11

EthanB


You can use this code:

using System.Net;

public long GetFileSize(string url)
{
    long result = 0;

    WebRequest req = WebRequest.Create(url);
    req.Method = "HEAD";
    using (WebResponse resp = req.GetResponse())
    {
        if (long.TryParse(resp.Headers.Get("Content-Length"), out long contentLength))
        {
            result = contentLength;
        }
    }

    return result;
}
like image 3
seyed Avatar answered Nov 20 '22 05:11

seyed


You can use an HttpWebRequest to query the HEAD Method of the file and check the Content-Length in the response

like image 2
Francis Avatar answered Nov 20 '22 05:11

Francis