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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With