C#使用MemoryStream類讀寫內(nèi)存
和FileStream一樣,MemoryStream和BufferedStream都派生自基類Stream,因此它們有很多共同的屬性和方法,但是每一個類都有自己獨特的用法。這兩個類都是實現(xiàn)對內(nèi)存進(jìn)行數(shù)據(jù)讀寫的功能,而不是對持久性存儲器進(jìn)行讀寫。
讀寫內(nèi)存-MemoryStream類
MemoryStream類用于向內(nèi)存而不是磁盤讀寫數(shù)據(jù)。MemoryStream封裝以無符號字節(jié)數(shù)組形式存儲的數(shù)據(jù),該數(shù)組在創(chuàng)建MemoryStream對象時被初始化,或者該數(shù)組可創(chuàng)建為空數(shù)組。可在內(nèi)存中直接訪問這些封裝的數(shù)據(jù)。內(nèi)存流可降低應(yīng)用程序中對臨時緩沖區(qū)和臨時文件的需要。下表列出了MemoryStream類的重要方法:
1、Read():讀取MemoryStream流對象,將值寫入緩存區(qū)。
2、ReadByte():從MemoryStream流中讀取一個字節(jié)。
3、Write():將值從緩存區(qū)寫入MemoryStream流對象。
4、WriteByte():從緩存區(qū)寫入MemoytStream流對象一個字節(jié)。
Read方法使用的語法如下:
- mmstream.Read(byte[] buffer,offset,count)
其中mmstream為MemoryStream類的一個流對象,3個參數(shù)中,buffer包含指定的字節(jié)數(shù)組,該數(shù)組中,從offset到(offset +count-1)之間的值由當(dāng)前流中讀取的字符替換。Offset是指Buffer中的字節(jié)偏移量,從此處開始讀取。Count是指最多讀取的字節(jié)數(shù)。Write()方法和Read()方法具有相同的參數(shù)類型。
MemoryStream類的使用實例:
- 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("努力學(xué)習(xí)");
- 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={0},Length={1},Position={2}\n",memStream.Capacity.ToString(),memStream.Length.ToString(),memStream.Position.ToString());
- 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關(guān)鍵字。注意:
using 關(guān)鍵字有兩個主要用途:
1、作為指令,用于為命名空間創(chuàng)建別名或?qū)肫渌臻g中定義的類型。
例如:
- using System;
2、作為語句,用于定義一個范圍,在此范圍的末尾將釋放對象。
- using(Connection conn=new Connection(connStr))
- {
- }
- //使用using關(guān)鍵字可及時銷毀對象
MemoryStream.Capacity 屬性 取得或設(shè)定配置給這個資料流的位元組數(shù)目。
MemoryStream.Position 屬性 指定當(dāng)前流的位置。
MemoryStream.Length 屬性獲取用字節(jié)表示的流長度。
SeekOrigin()是一個枚舉類,作用設(shè)定流的一個參數(shù)。
SeekOrigin.Begin我得理解就是文件的最開始,“0”是偏移,表示跳過0個字節(jié)。寫2就是跳過2個字節(jié)。
MemoryStream類通過字節(jié)讀寫數(shù)據(jù)。本例中定義了寫入的字節(jié)數(shù)組,為了更好的說明Write和WriteByte的異同,在代碼中聲明了兩個byte數(shù)組,其中一個數(shù)組寫入時調(diào)用Write方法,通過指定該方法的三個參數(shù)實現(xiàn)如何寫入。
另一個數(shù)組調(diào)用了WriteByte方法,每次寫入一個字節(jié),所以采用while循環(huán)來完成全部字節(jié)的寫入。寫入MemoryStream后,可以檢索該流的容量,實際長度,當(dāng)前流的位置,將這些值輸出到控制臺。通過觀察結(jié)果,可以確定寫入MemoryStream流是否成功。
調(diào)用Read和ReadByte兩種方法讀取MemoryStream流中的數(shù)據(jù),并將其進(jìn)行Unicode編碼后輸出到控制臺。
【編輯推薦】