[英]How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?
如何在C#中将 struct System.Byte
byte[]
转换为System.IO.Stream
对象?
将字节数组转换为流的最简单方法是使用MemoryStream
类:
Stream stream = new MemoryStream(byteArray);
You're looking for the MemoryStream.Write
method .您正在寻找
MemoryStream.Write
方法。
For example, the following code will write the contents of a byte[]
array into a memory stream:例如,以下代码会将
byte[]
数组的内容写入内存流:
byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream();
stream.Write(myByteArray, 0, myByteArray.Length);
Alternatively, you could create a new , non-resizable MemoryStream
object based on the byte array:或者,您可以基于字节数组创建一个新的、不可调整大小的
MemoryStream
对象:
byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream(myByteArray);
The general approach to write to any stream (not only MemoryStream
) is to use BinaryWriter
:写入任何流(不仅是
MemoryStream
)的一般方法是使用BinaryWriter
:
static void Write(Stream s, Byte[] bytes)
{
using (var writer = new BinaryWriter(s))
{
writer.Write(bytes);
}
}
查看MemoryStream
类。
If you are getting an error with the other MemoryStream examples here, then you need to set the Position to 0.如果您在此处的其他 MemoryStream 示例中遇到错误,则需要将 Position 设置为 0。
public static Stream ToStream(this bytes[] bytes)
{
return new MemoryStream(bytes)
{
Position = 0
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.