[.NET] BinaryWriter / BinaryReader

讀寫文檔可以以特定的編碼方式去讀,再以特定解碼方式去解讀出來。
BinaryWriter / BinaryRead 分別是利用特定的編碼方式,將基本資料型別當作二進位值來讀取。
System.IO.BinaryWriter:http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx
System.IO.BinaryReader:http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx

↓創建類別
System::IO::FileStream^ fs=gcnew System::IO::FileStream(PathString,System::IO::FileMode::OpenOrCreate, System::IO::FileAccess::ReadWrite);
//利用FileStream類別將文檔載入,並設定他的屬性、模式。
System::IO::BinaryWriter^ bw=gcnew System::IO::BinaryWriter(fs);
System::IO::BinaryReader^ br=gcnew System::IO::BinaryReader(fs);

↓利用BinaryWriter的Write方法將資料寫入 (多載。)
bw->Write(Boolean b); 一次寫入1 Byte到目前資料流。
bw->Write(Byte b); 
bw->Write(SByte b); 
bw->Write(Char b); 一次寫入2 Byte到目前資料流。(似乎和Encoding有關係,得再測試)
bw->Write(Int16 b); 一次寫入2 Byte到目前資料流。
bw->Write(UInt16 b);
bw->Write(Int64 b); 一次寫入8 Byte到目前資料流。
bw->Write(Int64 b);
bw->Write(Single b); 一次寫入4 Byte到目前資料流。
bw->Write(Int32 b); 
bw->Write(UInt32 b);
bw->Write(Single b); 
bw->Write(String b); 一次寫入有長度前置字元的字串到目前資料流。
bw->Write(Decimal b); 一次寫入16 Byte到目前資料流。

↓利用BinaryReader對應的讀取方法來讀取BinaryWriter寫的值。
br->ReadBoolean();
br->ReadByte();
br->ReadSByte();
br->ReadChar();
br->ReadInt16();
…每個都有相對應的讀取方法…

不過,要記錄的是…有時候使用Write方法,他並不會因為你的資料為char、wchar_t等就直接幫你假設為寫入其多載…建議要在寫入特定資料格式時在前方明確的定義,以免有跟我一樣…讀取一直有錯…。
當發現讀取檔案的內容有誤時,請明確定義資料格式為何,免得預想的讀取Byte數跟實際讀取Byte數不相同唷。
 
之後補上範例囉…

這個網誌中的熱門文章

[Tips] 設定桌面文字顏色

登入失敗: 使用者帳戶限制。可能原因為不允許空的密碼,登入時數限制,或強制的原則限制

[Win7] 電腦管理-損毀傾印