C# 从网络下载之前获取图像文件的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12079794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Size of Image File before downloading from web
提问by user1589754
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.
PS-实际上我已经编写了代码来制作一个在网站上移动下载图像文件的爬虫。所以我事先不知道它的大小。我所拥有的只是从网页源中提取的文件的完整路径。
回答by EthanB
If the web-service gives you a Content-LengthHTTP 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.
如果 Web 服务为您提供Content-LengthHTTP 标头,那么它将是图像文件的大小。但是,如果 Web 服务想要向您“流式传输”数据(使用块编码),那么在下载整个文件之前您不会知道。
回答by MethodMan
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
这是一个简单的示例,您可以尝试使用不同扩展名的文件,例如 .GIF、.JPG 等,您可以创建一个变量或将代码包装在 Switch Case 语句中
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");
回答by Perevalov
You should look at this answer: C# Get http:/…/File Sizewhere your question is fully explained. It's using HEAD HTTP request to retrieve the file size, but you can also read "Content-Length" header during GET request before reading response stream.
你应该看看这个答案:C# Get http:/.../File Size在这里你的问题得到了充分的解释。它使用 HEAD HTTP 请求来检索文件大小,但您也可以在读取响应流之前在 GET 请求期间读取“Content-Length”标头。
回答by Francis
You can use an HttpWebRequest to query the HEAD Method of the file and check the Content-Length in the response
您可以使用 HttpWebRequest 查询文件的 HEAD 方法并检查响应中的 Content-Length
回答by seyed
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;
}

