在C#中,可以通過以下方法將byte數組轉換為Stream或將Stream轉換為byte數組:
byte[] byteArray = { 0, 1, 2, 3, 4 };
MemoryStream memoryStream = new MemoryStream(byteArray);
MemoryStream memoryStream = new MemoryStream();
byte[] byteArray = memoryStream.ToArray();
注意:在將Stream轉換為byte數組時,需要確保Stream已經讀取完所有數據,并且重置Stream的位置到起始位置。
另外,可以使用BinaryWriter和BinaryReader來讀寫byte數組和Stream,具體代碼如下:
MemoryStream memoryStream = new MemoryStream();
BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
byte[] byteArray = { 0, 1, 2, 3, 4 };
binaryWriter.Write(byteArray);
MemoryStream memoryStream = new MemoryStream();
BinaryReader binaryReader = new BinaryReader(memoryStream);
byte[] byteArray = binaryReader.ReadBytes((int)memoryStream.Length);
這些方法可以幫助在C#中實現byte類型與Stream之間的互相轉換。