Skip to main content
 首页 » 编程设计

c#之WebResponse contentLength 属性是-1

2024年01月18日31sharpest

我有一个获取 URL 并下载 .jpeg 文件的 Windows 应用程序。对于某些 url,ContentLength 属性为 -1,因此会抛出异常。

这是我的代码:

var url = new Uri(sUrlToReadFileFrom[i]); 
_request = (HttpWebRequest)WebRequest.Create(url); 
var response = (System.Net.WebResponse)_request.GetResponse(); 
_response = response; 
_response.Close(); 

这是网址: http://photos.autonexus.com/imager/115-005-CA/P2GTPI4AB9/640/10132013133959/1FAHP0HA3AR373228_1.jpg 这是关于我的 http 请求的一些信息:

Headers = {Transfer-Encoding: chunked 
Connection: keep-alive 
Content-Disposition: inline; filename="phpThumb_generated_thumbnail.jpeg" 
Content-Type: image/jpeg 
Date: Wed, 12 Nov 2014 00:31:29 GMT 
Server: nginx 
X-Powered-By: PleskLin} 

我认为分块 header 导致了问题,但我已经用谷歌搜索了 2 天,但没有好的解决方案,或者我找不到好的解决方案。

这是错误的屏幕截图:

如您在第 130 行中所见,因为 _response.ContentLength 已经是 -1,因此 iSize 将为 -1,并在第 149 行抛出异常。

请您参考如下方法:

不要求站点提供 Content-Length header ,也不保证它是正确的。所以你不能依赖它。如果您尝试使用 ContentLength 属性值来分配一个数组,或者用于除了信息之外的任何目的,您将会遇到麻烦。在一般情况下,它根本不可靠。

这很不幸,但您必须解决它。一种解决方案是创建一个 MemoryStream。然后从响应流中读取数据 block 并将它们写入内存流。继续直到响应流结束。然后获取“MemoryStream”缓冲区。

有点痛苦,但如果 ContentLength 不可靠,这是您能做的最好的事情。

例如:(请注意,我只是把它扔掉了,所以它可能不是 100% 有效。但它应该给你想法。)

var response = (HttpWebResponse)request.GetResponse(); 
byte[] data; // will eventually hold the result 
// create a MemoryStream to build the result 
using (var mstrm = new MemoryStream()) 
{ 
    using (var s = response.GetResponseStream()) 
    { 
        var tempBuffer = new byte[4096]; 
        int bytesRead; 
        while ((bytesRead = s.Read(tempBuffer, 0, tempBuffer.Length)) != 0) 
        { 
            mstrm.Write(tempBuffer, 0, bytesRead); 
        } 
    } 
    mstrm.Flush(); 
    data = mstrm.GetBuffer(); 
} 
// at this point, the data[] array holds the data read from the stream. 
// data.Length will tell you how large it is.