错误“此流不支持搜索操作"在 C# 中

Error quot;This stream does not support seek operationsquot; in C#(错误“此流不支持搜索操作在 C# 中)
本文介绍了错误“此流不支持搜索操作"在 C# 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试使用 byte 流从 url 获取图像.但我收到此错误消息:

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

此流不支持搜索操作.

这是我的代码:

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?

推荐答案

您可能想要这样的东西.要么检查长度失败,要么 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# 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to know if a field is numeric in Linq To SQL(如何在 Linq To SQL 中知道字段是否为数字)
Extract sql query from LINQ expressions(从 LINQ 表达式中提取 sql 查询)
LINQ Where in collection clause(LINQ Where in collection 子句)
Orderby() not ordering numbers correctly c#(Orderby() 没有正确排序数字 c#)
Why do I get quot;error: ... must be a reference typequot; in my C# generic method?(为什么我会收到“错误:...必须是引用类型?在我的 C# 泛型方法中?)
Strange LINQ Exception (Index out of bounds)(奇怪的 LINQ 异常(索引越界))