从输入流创建字节数组的首选方法是什么?
下面是我目前使用。net 3.5的解决方案。
Stream s;
byte[] b;
using (BinaryReader br = new BinaryReader(s))
{
b = br.ReadBytes((int)s.Length);
}
读写流的块仍然是一个更好的主意吗?
从输入流创建字节数组的首选方法是什么?
下面是我目前使用。net 3.5的解决方案。
Stream s;
byte[] b;
using (BinaryReader br = new BinaryReader(s))
{
b = br.ReadBytes((int)s.Length);
}
读写流的块仍然是一个更好的主意吗?
当前回答
只是我的几毛钱……我经常使用的做法是将这些方法组织成一个自定义助手
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();
我可以把它写在一行字上:
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();
}
}
}
将命名空间添加到配置文件中,并在任何地方使用它
虽然Jon的回答是正确的,但他正在重写CopyTo中已经存在的代码。所以对于。net 4使用Sandip的解决方案,但是对于以前版本的。net使用Jon的答案。Sandip的代码将通过使用“using”作为CopyTo中的异常而得到改进,在许多情况下,很可能会留下MemoryStream不被处理。
public static byte[] ReadFully(Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
这是我正在使用的功能,测试和工作良好。 请记住“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;
}
}