Error “This stream does not support seek operations” in C#

后端 未结 7 805
梦毁少年i
梦毁少年i 2020-12-01 07:36

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.<

7条回答
  •  执笔经年
    2020-12-01 07:50

    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.

提交回复
热议问题