hello world!!!!!

写下自己的一些心得,写下自己问题的方式,写下程序之路的艰辛,希望能够有朝一日成为大牛。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

化繁就简,迎接2012的第一天!

Posted on 2012-01-01 12:29  陈力  阅读(539)  评论(0编辑  收藏  举报

 

 

化繁就简,迎接2012的第一天!

 

在下载网络图片的时候,一块很大的图片,你当然不可能一次下载完成,当然要块byte再紧接着块byte的下载

问题由此产生.....问题代码如下:

  using (var stream = response.GetResponseStream())
                {
                    int length = (int)response.ContentLength;
                    byte[] bytes = new byte[length];
                    int numBytesToRead = (int)length;
                    int numBytesRead = 0;

                    int readcount = 2000;
                    while (numBytesToRead > 0)
                    {
                                             // Read may return anything from 0 to 10.
                        int n = stream.Read(bytes, numBytesRead, readcount);
                        // The end of the file is reached.
                        if (n == 0)
                        {
                            return bytes;
                        }
                        numBytesRead += n;
                        numBytesToRead -= n;
                    }
                    return bytes;
                }
 大家没有注意到,当我们下载的时候,你读取请求的长度,是不能超过文件本身长度的,所以你请求指定位置的内容,不能超过它总的文件长度. (这个是http协议自身决定的,当然也可以在修改这个服务端的协议,一些大的公司,会在这细节上做修改)

 

正确的代码就是你在读取最后一块内容结束指定的长度为

 

                     if (numBytesRead + 2000 > length)
                        {
                            readcount = length - numBytesRead;
                        }

  华丽的分割线,以开始我2012年的第一天!