简体   繁体   English

如何在 C# 中将 struct System.Byte byte[] 转换为 System.IO.Stream 对象?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM