FileStream 核心成員
建構函式
public FileStream(string path, FileMode mode);
常用屬性
| 屬性 | 說明 |
| CanRead | 是否支援讀取 |
| CanSeek | 是否支援定位 |
| CanWrite | 是否支援寫入 |
| Handle | OS 檔案控制代碼 |
| IsAsync | 是否非同步開啟 |
| Length | 串流長度 (位元組) |
| Name | 檔案路徑 |
| Position | 目前位置 (可獲取/設定) |
常用方法
| 方法 | 說明 |
| BeginRead / EndRead | 非同步讀取 |
| BeginWrite / EndWrite | 非同步寫入 |
| Close | 關閉釋放資源 |
| Flush | 清空緩衝區寫入裝置 |
| Lock / Unlock | 鎖定/解鎖檔案區段 |
| Read / ReadByte | 讀取位元組區塊/單位元組 |
| Seek | 設定目前位置 |
| SetLength | 設定串流長度 |
| Write / WriteByte | 寫入位元組區塊/單位元組 |
BinaryReader 核心方法
public BinaryReader(Stream input);
讀取方法總表
| 方法 | 說明 |
| Read() | 讀取字元,推進位置 |
| ReadBoolean() | 讀取 Boolean (1 byte) |
| ReadByte() | 讀取下一位元組 |
| ReadBytes(int count) | 讀取指定數量位元組陣列 |
| ReadChar() | 讀取字元 |
| ReadChars(int count) | 讀取字元陣列 |
| ReadDecimal() | 讀取 Decimal (16 bytes) |
| ReadDouble() | 讀取 Double (8 bytes) |
| ReadInt16/32/64() | 讀取有號整數 (2/4/8 bytes) |
| ReadSByte() | 讀取有號位元組 |
| ReadSingle() | 讀取 Single (4 bytes) |
| ReadString() | 讀取長度前綴字串 |
| ReadUInt16/32/64() | 讀取無號整數 (Little Endian) |
BinaryWriter 核心方法
public BinaryWriter(Stream output);
常用方法
| 方法 | 說明 |
| Close() | 關閉寫入器與基底串流 |
| Flush() | 清空緩衝區 |
| Seek() | 設定串流位置 |
| Write() | 寫入各型別值 (多載) |
實例化範例
FileStream fs = new FileStream("C:\\temp.avi", FileMode.Open);
BinaryReader reader = new BinaryReader(fs);
BinaryWriter writer = new BinaryWriter(fs);
同步 vs 非同步
本系列採用同步模式:雖效能稍遜,但程式碼簡潔、不易出錯,適合教學與一般應用。