ใช้ MemoryStream (ใน System.IO) Wrap Byte Array ให้เป็น Stream
MemoryStream stream = new MemoryStream(byteArray);
ตัวอย่างอ่าน Byte Array ผ่าน Stream
using System;
using System.IO;
namespace DemoApplication
{
class Program
{
static void Main()
{
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();
}
}
}
Output
1 2 3 4 5
ประโยชน์ของ MemoryStream
- Seekable (สามารถ Position ได้)
- Performance ดี (อยู่ใน Memory)
- Implement Stream Interface ใช้กับ API ที่รับ Stream ได้เลย