是否可以使用webresponse在磁盘上检索文件大小? 如果没有,我怎么能检索文件大小?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(finalUrl);
request.AllowAutoRedirect = true;
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.ServicePoint.ConnectionLimit = 24;
//request.Method = "HEAD";
var contentType = string.Empty;
using (WebResponse webResponse = request.GetResponse())
{
contentType = webResponse.ContentType;
using (Stream stream = webResponse.GetResponseStream())
{
using (MemoryStream memoryStream = new MemoryStream())
{
Byte[] buffer = new Byte[1024];
Int32 bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Write(buffer, 0, bytesRead);
}
documentFile.Data = memoryStream.ToArray();
}
}
}
答案 0 :(得分:1)
我认为,在下载文件读取ContentLength
标题之前,这是从网站获取文件大小信息的唯一方法,并且无法保证服务器提供它。
var fileSize = webResponse.ContentLength;
或下载文件后,您可以获取流的长度以检索大小;
var fileSize = memoryStream.Length;