MemoryStream和BufferedStream都派生自基類Stream,因此它們有很多共同的屬性和方法,但是每一個類都有自己獨特的用法。這兩個類都是實現對內存進行數據讀寫的功能,而不是對持久性存儲器進行讀寫。
讀寫內存-MemoryStream類
MemoryStream類用於向內存而不是磁盤讀寫數據。MemoryStream封裝以無符號字節數組形式存儲的數據,該數組在創建MemoryStream對象時被初始化,或者該數組可創建為空數組。可在內存中直接訪問這些封裝的數據。內存流可降低應用程序中對臨時緩沖區和臨時文件的需要。
下表列出了MemoryStream類的重要方法:
1、Read():讀取MemoryStream流對象,將值寫入緩存區。
2、ReadByte():從MemoryStream流中讀取一個字節。
3、Write():將值從緩存區寫入MemoryStream流對象。
4、WriteByte():從緩存區寫入MemoytStream流對象一個字節。
Read方法使用的語法如下:
mmstream.Read(byte[] buffer,offset,count)
其中mmstream為MemoryStream類的一個流對象,3個參數中,buffer包含指定的字節數組,該數組中,從offset到(offset +count-1)之間的值由當前流中讀取的字符替換。Offset是指Buffer中的字節偏移量,從此處開始讀取。Count是指最多讀取的字節數。Write()方法和Read()方法具有相同的參數類型。
MemoryStream類的使用實例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ConsoleApplication1 { class Program { static void Main() { int count; byte[] byteArray; char[] charArray; UnicodeEncoding uniEncoding = new UnicodeEncoding(); // Create the data to write to the stream. byte[] firstString = uniEncoding.GetBytes("一二三四五"); byte[] secondString = uniEncoding.GetBytes("上山打老虎"); using (MemoryStream memStream = new MemoryStream(100)) { // Write the first string to the stream. memStream.Write(firstString, 0, firstString.Length); // Write the second string to the stream, byte by byte. count = 0; while (count < secondString.Length) { memStream.WriteByte(secondString[count++]); } // Write the stream properties to the console. Console.WriteLine("Capacity={0},Length={1},Position={2}\n", memStream.Capacity.ToString(), memStream.Length.ToString(), memStream.Position.ToString()); // Set the position to the beginning of the stream. memStream.Seek(0, SeekOrigin.Begin); // Read the first 20 bytes from the stream. byteArray = new byte[memStream.Length]; count = memStream.Read(byteArray, 0, 20); // Read the remaining bytes, byte by byte. while (count < memStream.Length) { byteArray[count++] = Convert.ToByte(memStream.ReadByte()); } // Decode the byte array into a char array // and write it to the console. charArray = new char[uniEncoding.GetCharCount(byteArray, 0, count)]; uniEncoding.GetDecoder().GetChars(byteArray, 0, count, charArray, 0); Console.WriteLine(charArray); Console.ReadKey(); } } } }