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

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

Stream s;
byte[] b;

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

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


当前回答

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

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

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

其他回答

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

MemoryStream ms = (MemoryStream)dataInStream;
byte[] imageBytes = ms.ToArray();
MemoryStream ms = new MemoryStream();
file.PostedFile.InputStream.CopyTo(ms);
var byts = ms.ToArray();
ms.Dispose();

我得到了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);
}

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

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

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

这是我正在使用的功能,测试和工作良好。 请记住“input”不应该是空的,而应该是“input”。Position '应该在读取之前重置为'0',否则它将打破读取循环,并且不会读取任何东西来转换为数组。

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

            return temp;
        }
    }