簡體   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);

您正在尋找MemoryStream.Write方法

例如,以下代碼會將byte[]數組的內容寫入內存流:

byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream();
stream.Write(myByteArray, 0, myByteArray.Length);

或者,您可以基於字節數組創建一個新的、不可調整大小的MemoryStream對象:

byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream(myByteArray);

寫入任何流(不僅是MemoryStream )的一般方法是使用BinaryWriter

static void Write(Stream s, Byte[] bytes)
{
    using (var writer = new BinaryWriter(s))
    {
        writer.Write(bytes);
    }
}

查看MemoryStream類。

如果您在此處的其他 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