在 C# 開發中,MemoryStream 類是處理記憶體資料流的核心工具。與 FileStream 和 BufferedStream 一樣,它都繼承自基類 Stream,因此擁有許多共同的屬性和方法。但不同的是,MemoryStream 專門用於在記憶體中而非磁碟上進行資料的讀寫操作,這大幅降低了應用程式對臨時緩衝區和臨時檔案的需求。
MemoryStream 封裝以無符號位元組陣列形式儲存的資料,該陣列在建立物件時初始化,或可建立為空陣列。開發者可直接在記憶體中存取這些封裝的資料,適合需要高速資料處理的場景。
| 方法 | 說明 |
|---|---|
| Read() | 從 MemoryStream 讀取資料到緩衝區 |
| ReadByte() | 從資料流讀取單一位元組 |
| Write() | 將緩衝區資料寫入 MemoryStream |
| WriteByte() | 將單一位元組寫入資料流 |
mmstream.Read(byte[] buffer, int offset, int count)
Write() 方法擁有相同的參數類型與結構。
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
int count;
byte[] byteArray;
char[] charArray;
UnicodeEncoding uniEncoding = new UnicodeEncoding();
byte[] firstString = uniEncoding.GetBytes("努力學習");
byte[] secondString = uniEncoding.GetBytes("不做C#中的菜鳥");
using (MemoryStream memStream = new MemoryStream(100))
{
// 寫入第一個字串
memStream.Write(firstString, 0, firstString.Length);
// 逐位元組寫入第二個字串
count = 0;
while (count < secondString.Length)
{
memStream.WriteByte(secondString[count++]);
}
// 輸出流資訊
Console.WriteLine($"Capacity={memStream.Capacity}, Length={memStream.Length}, Position={memStream.Position}\n");
// 重設位置並讀取資料
memStream.Seek(0, SeekOrigin.Begin);
byteArray = new byte[memStream.Length];
count = memStream.Read(byteArray, 0, 20);
while (count < memStream.Length)
{
byteArray[count++] = Convert.ToByte(memStream.ReadByte());
}
charArray = new char[uniEncoding.GetCharCount(byteArray, 0, count)];
uniEncoding.GetDecoder().GetChars(byteArray, 0, count, charArray, 0);
Console.WriteLine(charArray);
Console.ReadKey();
}
}
}
using System;SeekOrigin.Begin 表示資料流的起始位置,偏移量 0 代表不跳過任何位元組。此範例中使用 memStream.Seek(0, SeekOrigin.Begin) 將指標移回開頭以便讀取。
範例展示了兩種寫入方式的差異:
寫入完成後,程式碼檢索並輸出流的容量、實際長度與目前位置,以驗證寫入是否成功。隨後使用 Read() 與 ReadByte() 兩種方式讀取資料,經 Unicode 解碼後輸出至控制台。
MemoryStream 透過位元組層面操作資料,適用於需要高效能、避免磁碟 I/O 的暫存資料處理場景,是 C# 開發者工具箱中的利器。