2

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?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Code Ratchet
  • 5,758
  • 18
  • 77
  • 141
  • 2
    Use `CopyTo` as shown [here](https://stackoverflow.com/a/2934308/1563833) – Wyck Apr 22 '20 at 00:39
  • I've updated title to match your exception - please review and either edit to what you want to achieve (so post can be closed as duplicate of one @Wyck found) or maybe clarify why you expect behavior of `reader.BaseStream` to be different from behavior of the stream you started from. – Alexei Levenkov Apr 22 '20 at 00:45

2 Answers2

3

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;
Oguz Ozgul
  • 6,809
  • 1
  • 14
  • 26
0

You can also get the response size from the response header:

response.Headers["Content-Length"]
ozanmut
  • 2,898
  • 26
  • 22