创建从流的字节数组 [英] Creating a byte array from a stream

查看:125
本文介绍了创建从流的字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是prefered方法从输入流创建一个字节数组?

What is the prefered method for creating a byte array from an input stream?

下面是我目前的解决方案,.NET 3.5。

Here is my current solution with .NET 3.5.

Stream s;
byte[] b;

using (BinaryReader br = new BinaryReader(s))
{
    b = br.ReadBytes(s.Length);
}

仍然是一个更好的主意,读取和写入数据流的块?

Is it still a better idea to read and write chunks of the stream?

推荐答案

这真的取决于你是否信任 s.Length 。对于许多溪流,你只是不知道有多少数据会出现。在这种情况下,我会使用code是这样的:

It really depends on whether or not you can trust s.Length. For many streams, you just don't know how much data there will be. In such cases, I'd use code like this:

public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16*1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

编辑:我也许应该解释为什么我的答案是比别人更长的时间。 Stream.Read 并不能保证它会读到的一切它的问对于。如果你从网络流中读取数据,例如,它可以读取一个数据包的价值,然后返回,即使会有更多的数据很快。 <一href="http://msdn.microsoft.com/en-us/library/system.io.binaryreader.read.aspx">BinaryReader.Read将继续下去,直到流或您指定大小的结束,但你还是要知道下手的大小。

I should perhaps explain why my answer is longer than the others. Stream.Read doesn't guarantee that it will read everything it's asked for. If you're reading from a network stream, for example, it may read one packet's worth and then return, even if there will be more data soon. BinaryReader.Read will keep going until the end of the stream or your specified size, but you still have to know the size to start with.

以上方法将继续读(和复制到MemoryStream),直到它运行的数据。然后它要求将MemoryStream返回数据的拷贝在一个阵列。如果你知道开始与大小 - 或认为的,你知道的大小,而不肯定的 - 你可以构造MemoryStream的是该大小的开始。同样可以把一个检查结束时,如果该流的长度尺寸相同的缓冲液(由<返回的href="http://msdn.microsoft.com/en-us/library/system.io.memorystream.getbuffer.aspx">MemoryStream.GetBuffer)那么你可以返回缓冲区所以上面的code不是很优化,但至少会是正确的它不承担任何责任为关闭流 - 。来电者应该做的。

The above method will keep reading (and copying into a MemoryStream) until it runs out of data. It then asks the MemoryStream to return a copy of the data in an array. If you know the size to start with - or think you know the size, without being sure - you can construct the MemoryStream to be that size to start with. Likewise you can put a check at the end, and if the length of the stream is the same size as the buffer (returned by MemoryStream.GetBuffer) then you can just return the buffer. So the above code isn't quite optimised, but will at least be correct. It doesn't assume any responsibility for closing the stream - the caller should do that.

请参阅这篇文章更多信息(和一个可选的实现)。

See this article for more info (and an alternative implementation).

这篇关于创建从流的字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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