从输入流创建字节数组的首选方法是什么?

下面是我目前使用。net 3.5的解决方案。

Stream s;
byte[] b;

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

读写流的块仍然是一个更好的主意吗?


当前回答

你可以简单地使用MemoryStream类的ToArray()方法,对于ex-

MemoryStream ms = (MemoryStream)dataInStream;
byte[] imageBytes = ms.ToArray();

其他回答

我得到了Bob(即提问者)代码的编译时错误。流。Length是一个长而BinaryReader。ReadBytes接受一个整型参数。在我的情况下,我不期望处理足够大的流,需要很长的精度,所以我使用以下:

Stream s;
byte[] b;

if (s.Length > int.MaxValue) {
  throw new Exception("This stream is larger than the conversion algorithm can currently handle.");
}

using (var br = new BinaryReader(s)) {
  b = br.ReadBytes((int)s.Length);
}
MemoryStream ms = new MemoryStream();
file.PostedFile.InputStream.CopyTo(ms);
var byts = ms.ToArray();
ms.Dispose();

我可以把它写在一行字上:

byte [] byteArr= ((MemoryStream)localStream).ToArray();

正如johnnyRose澄清的那样,以上代码只适用于MemoryStream

只是我的几毛钱……我经常使用的做法是将这些方法组织成一个自定义助手

public static class StreamHelpers
{
    public static byte[] ReadFully(this Stream input)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            input.CopyTo(ms);
            return ms.ToArray();
        }
    }
}

将命名空间添加到配置文件中,并在任何地方使用它

你可以简单地使用MemoryStream类的ToArray()方法,对于ex-

MemoryStream ms = (MemoryStream)dataInStream;
byte[] imageBytes = ms.ToArray();