从输入流创建字节数组的首选方法是什么?
下面是我目前使用。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);
}
读写流的块仍然是一个更好的主意吗?
当前回答
我得到了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);
}
其他回答
虽然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();
}
}
我得到了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);
}
这是我正在使用的功能,测试和工作良好。 请记住“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;
}
}
将两个投票最多的答案组合成一个扩展方法:
public static byte[] ToByteArray(this Stream stream)
{
if (stream is MemoryStream)
return ((MemoryStream)stream).ToArray();
else
{
using MemoryStream ms = new();
stream.CopyTo(ms);
return ms.ToArray();
}
}
MemoryStream ms = new MemoryStream();
file.PostedFile.InputStream.CopyTo(ms);
var byts = ms.ToArray();
ms.Dispose();