错误“此流不支持查找操作”。在C#中 [英] Error "This stream does not support seek operations" in C#

查看:155
本文介绍了错误“此流不支持查找操作”。在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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.

这是我的代码:

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;

我在做什么错人?

推荐答案

您可能想要这样的东西。要么检查长度失败,要么BinaryReader在后台进行查找。

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();
}

编辑:

我使用反射器检查了,这是对stream.Length的调用失败。 GetResponseStream返回一个ConnectStream,并且该类的Length属性引发您看到的异常。正如其他张贴者所提到的那样,您无法可靠地获取HTTP响应的长度,所以这是有道理的。

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.

这篇关于错误“此流不支持查找操作”。在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆