Can't download complete image file from skydrive using REST API

倾然丶 夕夏残阳落幕 提交于 2019-12-04 21:55:54

This is because you don't check the return value of responseStream.Read(contents, 0, (int)response.ContentLength);. Read doesn't ensure that it will read response.ContentLength bytes. Instead it returns the number of bytes read. You can use a loop or stream.CopyTo there.

Something like this:

WebResponse response = request.GetResponse();
MemoryStream m = new MemoryStream();
response.GetResponseStream().CopyTo(m);
byte[] contents = m.ToArray();

As LB already said, you need to continue to call Read() until you have read the entire stream.

Although Stream.CopyTo will copy the entire stream it does not ensure that read the number of bytes expected. The following method will solve this and raise an IOException if it does not read the length specified...

    public static void Copy(Stream input, Stream output, long length)
    {
        byte[] bytes = new byte[65536];
        long bytesRead = 0;
        int len = 0;
        while (0 != (len = input.Read(bytes, 0, Math.Min(bytes.Length, (int)Math.Min(int.MaxValue, length - bytesRead)))))
        {
            output.Write(bytes, 0, len);
            bytesRead = bytesRead + len;
        }
        output.Flush();
        if (bytesRead != length)
            throw new IOException();
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!