【问题标题】:Reading A stream through stream.read instead of using a StreamReader通过 stream.read 而不是使用 StreamReader 读取流
【发布时间】:2012-03-18 11:19:44
【问题描述】:

我正在尝试获取请求并将其读取为:

byte[] buffer;
Stream read = http.GetResponseStream();
string readIt = read.Read(buffer, 0, read.Length)

但它会抛出参数无效的错误。

知道如何在使用 Stream 而不是 StreamReader 时获得对字符串的响应吗?

【问题讨论】:

  • 它应该拒绝编译(未分配buffer
  • @HenkHolterman:并尝试将int 转换为string :)

标签: c# stream io httpwebrequest


【解决方案1】:

那是因为你还没有创建你尝试使用的字节数组。

byte[] buffer = new byte[read.Length];

请注意,您应该在使用之前检查read.Length 的值。响应长度并不总是已知的。

另外,Read 方法返回一个int,而不是一个string

另外,这非常重要,您必须使用来自Read 方法的返回值,因为它告诉您实际读取了多少字节。 Read 方法不必返回您要求的所有字节,因此您必须循环直到它返回值为零,这意味着流已被读取到最后:

int offset = 0, len;
do {
  len = read.Read(buffer, offset, read.Length - offset);
  offset += len;
} while (len > 0);

// now offset contains the number of bytes read into the buffer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 2015-02-23
    • 2012-12-14
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多