Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

stream

byte

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?

like image 884
Yustme Avatar asked Aug 08 '10 10:08

Yustme


2 Answers

You probably want something like this. Either checking the length fails, or the BinaryReader is doing seeks behind the scenes.

HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url); WebResponse myResp = myReq.GetResponse();  byte[] b = null; using( Stream stream = myResp.GetResponseStream() ) using( MemoryStream ms = new MemoryStream() ) {   int count = 0;   do   {     byte[] buf = new byte[1024];     count = stream.Read(buf, 0, 1024);     ms.Write(buf, 0, count);   } while(stream.CanRead && count > 0);   b = ms.ToArray(); } 

edit:

I checked using reflector, and it is the call to stream.Length that fails. GetResponseStream returns a ConnectStream, and the Length property on that class throws the exception that you saw. As other posters mentioned, you cannot reliably get the length of a HTTP response, so that makes sense.

like image 123
ngoozeff Avatar answered Sep 22 '22 06:09

ngoozeff


Use a StreamReader instead:

HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url); WebResponse myResp = myReq.GetResponse();  StreamReader reader = new StreamReader(myResp.GetResponseStream()); return reader.ReadToEnd(); 

(Note - the above returns a String instead of a byte array)

like image 38
Justin Avatar answered Sep 19 '22 06:09

Justin