首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

.NET 檔案 I/O 完整指南:File、Directory、FileStream、StreamReader/Writer 實戰

     編輯:關於C語言

核心類別速查表

類別命名空間定位關鍵成員
FileSystem.IO靜態工具類,操作實體檔案Copy, Create, Delete, Exists, Move, Open, ReadAllText, WriteAllText
DirectorySystem.IO靜態工具類,操作目錄CreateDirectory, Delete, Exists, GetDirectories, GetFiles, Move
PathSystem.IO路徑字串處理Combine, GetFileName, GetDirectoryName, GetExtension, ChangeExtension, GetTempPath
FileInfoSystem.IO檔案實例資訊與操作Length, CreationTime, DirectoryName, Exists, Open, OpenRead, OpenWrite, CopyTo, MoveTo, Delete
DirectoryInfoSystem.IO目錄實例資訊與操作GetFiles, GetDirectories, CreateSubdirectory, Delete, MoveTo
FileStreamSystem.IO位元組串流,支援同步/非同步、隨機存取Read, Write, Seek, Position, Length, Flush, Lock, Unlock
StreamReaderSystem.IO文字讀取器(字元解碼),包裝 StreamRead, ReadLine, ReadToEnd, CurrentEncoding, EndOfStream
StreamWriterSystem.IO文字寫入器(字元編碼),包裝 StreamWrite, WriteLine, Flush, AutoFlush, Encoding
FileSystemWatcherSystem.IO監控檔案系統變更事件Changed, Created, Deleted, Renamed, EnableRaisingEvents, Filter, IncludeSubdirectories

路徑處理最佳實務

  • 永遠使用 Path.Combine 組合路徑,避免手工拼接 \\ 或 /。
  • 相對路徑基於 AppDomain.CurrentDomain.BaseDirectory (EXE 目錄) 或 Environment.CurrentDirectory。
  • 跨平台:.NET Core 預設支援 Unix 路徑分隔符,Path.DirectorySeparatorChar 自動適配。

FileStream 進階操作

// 開啟/建立模式
var fs = new FileStream("data.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);

// 隨機存取
fs.Seek(100, SeekOrigin.Begin); // 從開頭偏移 100 位元組
fs.Seek(-50, SeekOrigin.End);   // 從結尾倒數 50 位元組
fs.Seek(10, SeekOrigin.Current); // 從目前位置偏移 10

// 讀寫位元組陣列
byte[] buffer = new byte[1024];
int read = fs.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, read);

// 非同步 (高併發必備)
await fs.ReadAsync(buffer, 0, buffer.Length);
await fs.WriteAsync(buffer, 0, read);

StreamReader/Writer 文字處理範例

讀取全文

string text = File.ReadAllText("log.txt", Encoding.UTF8); // 簡便
// 或大檔案逐行
using (var sr = new StreamReader("big.log", Encoding.UTF8))
{
    string line;
    while ((line = sr.ReadLine()) != null) Process(line);
}

寫入文字

// 覆寫
File.WriteAllText("out.txt", "Hello", Encoding.UTF8);
// 附加
using (var sw = new StreamWriter("out.txt", true, Encoding.UTF8)) // append = true
{
    sw.WriteLine("Line 1");
    sw.Write("Line 2 ");
    sw.Write("continued");
}

CSV 解析 (StreamReader + Split)

using (var sr = new StreamReader("data.csv"))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        string[] fields = line.Split(',');
        // 若欄位含逗號/引號,請使用 TextFieldParser (Microsoft.VisualBasic.FileIO) 或 CsvHelper 套件
    }
}

FileSystemWatcher 監控範例

var watcher = new FileSystemWatcher(@"C:\Inbox")
{
    Filter = "*.xml",
    IncludeSubdirectories = true,
    EnableRaisingEvents = true
};
watcher.Created += (s, e) => Console.WriteLine($"新增: {e.FullPath}");
watcher.Changed += (s, e) => Console.WriteLine($"變更: {e.FullPath} ({e.ChangeType})");
watcher.Renamed += (s, e) => Console.WriteLine($"重命名: {e.OldFullPath} -> {e.FullPath}");
// 注意: 事件在背景執行緒觸發,UI 更新需 Invoke/Dispatcher

常見陷阱與解決方案

問題原因解決
檔案被鎖定無法存取未正確 Dispose Stream/Reader/Writer全程使用 using 區塊確保釋放
中文亂碼編碼不一致 (預設 UTF-8 vs ANSI)明確指定 Encoding.UTF8 或 Encoding.GetEncoding("GB2312")
大檔案 OOMReadAllText 一次載入記憶體改用 StreamReader.ReadLine 逐行或 FileStream 分塊處理
路徑過長 (>260)Windows MAX_PATH 限制啟用 Long Path (組態/登錄) 或使用 \\?\ 前綴
非同步死結.Result / .Wait() 造成同步阻塞全程 async/await,避免同步等待

.NET 6+ 現代 API 亮點

  • File.ReadAllLinesAsync、File.WriteAllTextAsync 內建非同步。
  • Path.Join 多段組合、Path.GetRelativePath 計算相對路徑。
  • RandomAccess 類別:無需開啟 FileStream 即可隨機讀寫 (高效能)。
  • File.OpenHandle 取得 SafeFileHandle 進行低層級 I/O。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved