Error "This stream does not support seek operations" in C#

Viewed 96331

I'm trying to get an image from an url using a byte stream. But i get this error message:

This stream does not support seek operations.

This is my code:

byte[] b;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
WebResponse myResp = myReq.GetResponse();

Stream stream = myResp.GetResponseStream();
int i;
using (BinaryReader br = new BinaryReader(stream))
{
    i = (int)(stream.Length);
    b = br.ReadBytes(i); // (500000);
}
myResp.Close();
return b;

What am i doing wrong guys?

7 Answers

Perhaps you should use the System.Net.WebClient API. If already using client.OpenRead(url) use client.DownloadData(url)

var client = new System.Net.WebClient();
byte[] buffer = client.DownloadData(url);
using (var stream = new MemoryStream(buffer))
{
    ... your code using the stream ...
}

Obviously this downloads everything before the Stream is created, so it may defeat the purpose of using a Stream. webClient.DownloadData("https://your.url") gets a byte array which you can then turn into a MemoryStream.

Related