我该如何准确地读取n从字节流? [英] How do I read exactly n bytes from a stream?
问题描述
这是一个有点棘手,比我想象中的第一。我试图从流中读取n个字节。
This is a little more tricky than I first imagined. I'm trying to read n bytes from a stream.
借助声称的读不必返回n个字节,它只是必须返回至少1和最多n个字节,0字节是到达流的端部的特殊情况。
The MSDN claims that Read does not have to return n bytes, it just must return at least 1 and up to n bytes, with 0 bytes being the special case of reaching the end of the stream.
通常情况下,我使用的是类似
Typically, I'm using something like
var buf = new byte[size];
var count = stream.Read (buf, 0, size);
if (count != size) {
buf = buf.Take (count).ToArray ();
}
yield return buf;
我希望的正是尺寸
字节,但通过规范的FileStream将被允许返回了大量的1字节的块为好。这必须加以避免。
I'm hoping for exactly size
bytes but by spec FileStream would be allowed to return a large number of 1-byte chunks as well. This must be avoided.
要解决,这将是有2缓冲器,一个用于读出和一个用于收集块,直到我们得到请求的字节数的一种方式。这是一个有点麻烦,但。
One way to solve this would be to have 2 buffers, one for reading and one for collecting the chunks until we got the requested number of bytes. That's a little cumbersome though.
我也看了一下 BinaryReader在,但其规格也做没有明确指出n个字节将肯定返回。
I also had a look at BinaryReader but its spec also does not clearly state that n bytes will be returned for sure.
要澄清:当然,在数据流的末尾字节,返回的数字可能小于尺寸
- 这不是一个问题。我只谈论没有接获任何即使他们是在流中可用的字节。
To clarify: Of course, upon the end of the stream the returned number of bytes may be less than size
- that's not a problem. I'm only talking about not receiving n bytes even though they are available in the stream.
推荐答案
一个稍微更可读的版本:
A slightly more readable version:
int offset = 0;
while (offset < count)
{
int read = stream.Read(buffer, offset, count - offset);
if (read == 0)
throw new System.IO.EndOfStreamException();
offset += read;
}
或书面作为流
类的扩展方法:
public static class StreamUtils
{
public static byte[] ReadExactly(this System.IO.Stream stream, int count)
{
byte[] buffer = new byte[count];
int offset = 0;
while (offset < count)
{
int read = stream.Read(buffer, offset, count - offset);
if (read == 0)
throw new System.IO.EndOfStreamException();
offset += read;
}
System.Diagnostics.Debug.Assert(offset == count);
return buffer;
}
}
这篇关于我该如何准确地读取n从字节流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!