萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# FileStream 核心屬性、方法與檔案操作模式完整速查表

命名空間

using System.IO;

常用屬性

屬性型別說明
CanReadbool流是否支援讀取
CanWritebool流是否支援寫入
CanSeekbool流是否支援定位 (檔案通常為 true,網路流通常為 false)
Lengthlong流長度 (位元組),需 CanSeek=true
Positionlong當前指標位置,可獲取/設定,需 CanSeek=true

核心方法

方法簽名說明
Readint Read(byte[] buffer, int offset, int count)讀取最多 count 位元組到 buffer,返回實際讀取數;0 表示 EOF
ReadAsyncTask ReadAsync(byte[] buffer, int offset, int count, CancellationToken ct)非同步讀取,**建議優先使用**
Writevoid Write(byte[] buffer, int offset, int count)寫入 buffer 指定範圍
WriteAsyncTask WriteAsync(byte[] buffer, int offset, int count, CancellationToken ct)非同步寫入
Seeklong Seek(long offset, SeekOrigin origin)移動指標:Begin/Current/End
Flushvoid Flush()清空緩衝區至作業系統 (不保證寫入實體磁碟)
FlushAsyncTask FlushAsync(CancellationToken ct)非同步刷新
Closevoid Close()關閉流、釋放控制碼 (等同 Dispose())

檔案開啟模式枚舉 (FileMode)

枚舉值行為典型場景
CreateNew新建,存在則拋異常獨佔建立,防覆蓋
Create新建,存在則**截斷覆蓋**寫入新內容 (最常用)
Open開啟現有,不存在拋異常讀取/修改既有檔案
OpenOrCreate開啟現有,不存在則新建讀寫通用、不想處理不存在例外
Append開啟現有並定位至末尾,不存在則新建,**只能搭配 FileAccess.Write**日誌追加、斷點續傳
Truncate開啟現有並**清空內容** (長度歸零)重寫整個檔案

檔案存取權限 (FileAccess)

  • Read、Write、ReadWrite
  • 必須與 FileMode 邏輯相容 (如 Append 僅能搭配 Write)。

檔案共享模式 (FileShare) — 關鍵併發控制

枚舉值允許其他進程典型用途
None無 (獨佔)獨佔寫入、安裝程式替換檔案
Read讀取多進程同時讀日誌/設定檔
Write寫入極少用,易造成資料損毀
ReadWrite讀寫高併發日誌、資料庫檔案 (需應用層協調)
Delete刪除檔案允許其他進程刪除已開啟檔案
Inheritable子進程繼承控制碼進程間傳遞檔案控制碼

建構子多載 (常用三種)

// 1. 最簡單
new FileStream(path, FileMode.Create)

// 2. 指定存取權限
new FileStream(path, FileMode.Create, FileAccess.Write)

// 3. 完整控制
new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true)

建議: 高效能 I/O 啟用 useAsync: true (Windows 使用 IOCP),緩衝區 4K-64K。

File 靜態工廠方法 (更簡潔)

方法等價 FileStream 建構適用場景
File.OpenRead(path)new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)唯讀共享
File.OpenWrite(path)new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None)追加寫入
File.Open(path, mode)自訂模式,預設 ReadWrite + Read 共享需精確控制時

標準讀寫模板 (using 確保釋放)

讀取文字檔

using (var fs = File.OpenRead(path)) 
using (var sr = new StreamReader(fs, Encoding.UTF8)) {
    string content = await sr.ReadToEndAsync();
    // 處理內容
}

寫入文字檔

using (var fs = File.OpenWrite(path)) 
using (var sw = new StreamWriter(fs, new UTF8Encoding(false))) { // 無 BOM
    await sw.WriteAsync(content);
}

二進位複製 (高效能)

using (var src = File.OpenRead(srcPath))
using (var dst = File.OpenWrite(dstPath)) {
    await src.CopyToAsync(dst); // 內部使用 4096 緩衝區
}

常見坑點

  • 未使用 using/try-finally → 檔案鎖定、資源洩漏。
  • Append 模式搭配 ReadWrite → 異常。
  • Position 設定超出 Length → 寫入會擴展檔案 (中間補 0),讀取拋異常。
  • Flush ≠ 寫入磁碟:需 FileOptions.WriteThrough 或 Flush() + Handle.FlushFileBuffers() (P/Invoke) 保證持久化。
  • 大檔案一次性 ReadAllBytes → LOH 壓力、OOM 風險,改用流式分塊處理。

結語

FileStream 是 .NET 底層 I/O 基石。熟記 FileMode/FileAccess/FileShare 三維組合、優先使用 Async 版本**、善用 File 工廠方法與 StreamReader/Writer 封裝,能寫出正確、高效、併發安全的檔案操作代碼。

copyright © 萬盛學電腦網 all rights reserved