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

C# 檔案操作完全指南:建立、讀取、附加與最佳實務模式

     編輯:關於C語言

核心類別總覽

.NET 在 System.IO 命名空間提供豐富的檔案操作類別:

  • File:靜態方法,一次性操作(建立、複製、刪除、開啟)
  • FileInfo:執行個體方法,適合多次操作同一檔案
  • StreamWriter / StreamReader:文字串流寫入/讀取
  • FileStream:位元組層級隨機存取
  • Path:跨平台路徑處理

範例一:建立文字檔並寫入內容

using System;
using System.IO;

public class FileCreator
{
    public static void CreateTextFile(string path, params string[] lines)
    {
        // using 確保自動關閉與釋放資源
        using (StreamWriter writer = File.CreateText(path))
        {
            foreach (var line in lines)
            {
                writer.WriteLine(line);
            }
        }
        Console.WriteLine($"檔案已建立: {path}");
    }
}

// 呼叫
FileCreator.CreateTextFile(@"C:\Temp\MyTextFile.txt", 
    "God is greatest of them all", 
    "This is second line");

關鍵點

  • File.CreateText 回傳 StreamWriter,預設 UTF-8 編碼
  • using 區塊等同 try/finally 呼叫 Dispose()
  • 路徑使用 @ 字串常值避免跳脫字元問題

範例二:逐行讀取文字檔

public static void ReadTextFile(string path)
{
    if (!File.Exists(path))
    {
        Console.WriteLine("檔案不存在");
        return;
    }

    using (StreamReader reader = File.OpenText(path))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            Console.WriteLine(line);
        }
    }
}

進階讀取模式

// 一次讀取所有行(小檔案適用)
string[] allLines = File.ReadAllLines(path, Encoding.UTF8);

// 一次讀取整個內容
string content = File.ReadAllText(path);

// 非同步讀取(.NET 4.5+,避免阻塞 UI 執行緒)
string contentAsync = await File.ReadAllTextAsync(path);

範例三:附加內容至現有檔案

public static void AppendToFile(string path, string content)
{
    // File.AppendText 開啟檔案並移至末尾
    using (StreamWriter writer = File.AppendText(path))
    {
        writer.WriteLine(content);
    }
    Console.WriteLine("內容已附加");
}

// 呼叫
AppendToFile(@"C:\Temp\MyTextFile.txt", "This Line Is Appended");

最佳實務與進階技巧

1. 編碼明確指定

// 寫入指定編碼
using (var writer = new StreamWriter(path, false, Encoding.GetEncoding("big5")))
{
    writer.WriteLine("繁體中文內容");
}

// 讀取指定編碼
using (var reader = new StreamReader(path, Encoding.GetEncoding("big5")))
{
    string text = reader.ReadToEnd();
}

2. 大檔案處理:串流與緩衝

// 使用 FileStream + StreamReader/Writer 手動控制緩衝區大小
const int BufferSize = 64 * 1024; // 64KB
using (var fs = new FileStream(largeFile, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize))
using (var reader = new StreamReader(fs, Encoding.UTF8, true, BufferSize))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // 處理每一行...
    }
}

3. 非同步 I/O(.NET 4.5+)

public async Task WriteLargeFileAsync(string path, IEnumerable data)
{
    using (var writer = new StreamWriter(path, false, Encoding.UTF8, 4096))
    {
        foreach (var line in data)
        {
            await writer.WriteLineAsync(line);
        }
    }
}

4. 暫存檔案與原子性寫入

public static void AtomicWrite(string targetPath, string content)
{
    string tempPath = Path.GetTempFileName();
    try
    {
        File.WriteAllText(tempPath, content, Encoding.UTF8);
        // Replace 原子性取代目標檔案(Windows 支援)
        File.Replace(tempPath, targetPath, null, true);
    }
    finally
    {
        if (File.Exists(tempPath)) File.Delete(tempPath);
    }
}

5. 路徑處理最佳實務

// 組合路徑(自動處理分隔符號)
string fullPath = Path.Combine(baseDir, "sub", "file.txt");

// 取得副檔名、檔名、目錄
string ext = Path.GetExtension(fullPath);      // ".txt"
string name = Path.GetFileNameWithoutExtension(fullPath); // "file"
string dir = Path.GetDirectoryName(fullPath);

// 取得特殊資料夾
string docs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string temp = Path.GetTempPath();

例外處理與錯誤代碼

例外類型常見原因
FileNotFoundException檔案不存在
DirectoryNotFoundException目錄路徑無效
UnauthorizedAccessException權限不足、檔案被鎖定
IOException磁碟空間不足、網路中斷、共用違規
PathTooLongException路徑超過 260 字元(可啟用長路徑支援)
try
{
    File.Copy(src, dest, true);
}
catch (UnauthorizedAccessException ex)
{
    Log.Error("權限不足", ex);
    throw new ApplicationException("無法存取檔案,請檢查權限", ex);
}
catch (IOException ex) when ((ex.HResult & 0xFFFF) == 32) // ERROR_SHARING_VIOLATION
{
    Log.Error("檔案被其他程式佔用", ex);
    // 可重試邏輯...
}

總結

C# 檔案操作核心在於:善用 using 區塊管理資源、明確指定編碼、大檔案用串流、UI 執行緒用非同步、關鍵資料用原子性寫入。掌握 File/FileInfo、StreamReader/Writer、FileStream 等類別的適用場景,即能高效、安全地處理各類檔案 I/O 需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved