如何在 C# 中將位元組陣列轉換為物件流?
Stream 是所有流的抽象基類,可提供位元組序列的通用檢視。流物件涉及三個基本操作,即讀取、寫入和查詢。可以重置流,從而提高效能。
可以使用 MemoryStream 類將位元組陣列轉換為記憶體流。
MemoryStream stream = new MemoryStream(byteArray);
示例
我們考慮一個包含 5 個值 1、2、3、4、5 的位元組陣列。
using System; using System.IO; namespace DemoApplication { class Program { static void Main(string[] args) { byte[] byteArray = new byte[5] {1, 2, 3, 4, 5 }; using (MemoryStream stream = new MemoryStream(byteArray)) { using (BinaryReader reader = new BinaryReader(stream)) { for (int i = 0; i < byteArray.Length; i++) { byte result = reader.ReadByte(); Console.WriteLine(result); } } } Console.ReadLine(); } } }
輸出
以上程式碼的輸出為
1 2 3 4 5
廣告