Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream returned by Http response is not seekable as response.Length throws "unsupported"

Tags:

c#

stream

binary

I'm trying to read the bytes from a file that I've retrieved from an external source, however when running the code I get the following error:

System.NotSupportedException: Specified method is not supported.\r\n   at System.Net.Http.HttpBaseStream.get_Length()

My code in question is as follows:

var responseBody = (request.GetResponseAsync().Result).GetResponseStream();

        byte[] file;
        var br = new BinaryReader(responseBody);
        file = br.ReadBytes((int)br.BaseStream.Length);
        using (MemoryStream ms = new MemoryStream())
        {
            int read;
            while ((read = responseBody.Read(file, 0, file.Length)) > 0)
            {
                ms.Write(file, 0, read);
            }
        }

        var result = new MemoryStream(file);

It fails on the following line:

  file = br.ReadBytes((int)br.BaseStream.Length);

I can't seem to find a solution to the issue, can anyone suggest a fix?

like image 247
Code Ratchet Avatar asked Oct 16 '25 10:10

Code Ratchet


1 Answers

The stream you feed into the binary reader is not seekable. You can check the CanSeek property to see this.

For example, when chunked encoding is used by the server to return the response, there is no way to know the file size beforehand.

Try this. You are already reading from the response stream, and not from the BinaryReader.

Note: You can also use CopyTo()

var responseBody = (request.GetResponseAsync().Result).GetResponseStream();

byte[] tempBuffer = new byte[8192];
MemoryStream ms = new MemoryStream();
int read;
while ((read = responseBody.Read(tempBuffer, 0, tempBuffer.Length)) > 0)
{
    ms.Write(tempBuffer, 0, read);
}

var result = ms;
like image 189
Oguz Ozgul Avatar answered Oct 17 '25 23:10

Oguz Ozgul