萬盛學電腦網

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

C# 文字檔讀寫完整指南:StreamReader/Writer 實戰範例

核心類別架構

.NET 透過 System.IO 命名空間提供檔案 I/O 功能。基礎抽象為 Stream (位元組串流),上層封裝 StreamReader/StreamWriter 處理文字編碼轉換,支援 FileStream (檔案) 與 MemoryStream (記憶體) 等多種後端。

完整 WinForms 範例:讀取、取代、儲存

using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace TextFileDemo {
    public partial class Form1 : Form {
        public Form1() { InitializeComponent(); }

        // 讀取檔案 (支援 GB2312 編碼)
        private void btn_Read_Click(object sender, EventArgs e) {
            try {
                using (var fs = new FileStream(tB_PachFileName.Text, FileMode.Open, FileAccess.Read))
                using (var sr = new StreamReader(fs, Encoding.GetEncoding("GB2312"))) {
                    rTB_Display.Text = "";
                    string line;
                    while ((line = sr.ReadLine()) != null) {
                        rTB_Display.Text += line + Environment.NewLine;
                    }
                }
            } catch (Exception ex) {
                MessageBox.Show("讀取失敗: " + ex.Message);
            }
        }

        // 字串取代
        private void btn_Replace_Click(object sender, EventArgs e) {
            if (string.IsNullOrEmpty(tB_Replace.Text) && string.IsNullOrEmpty(tB_Replace_2.Text)) {
                MessageBox.Show("請輸入欲取代的文字");
                return;
            }
            if (string.IsNullOrEmpty(rTB_Display.Text)) {
                MessageBox.Show("內容為空");
                return;
            }
            rTB_Display.Text = rTB_Display.Text.Replace(tB_Replace.Text, tB_Replace_2.Text);
        }

        // 儲存檔案 (預設 UTF-8 無 BOM)
        private void btn_Save_Click(object sender, EventArgs e) {
            try {
                using (var fs = new FileStream(tB_Save.Text, FileMode.OpenOrCreate, FileAccess.Write))
                using (var sw = new StreamWriter(fs, new UTF8Encoding(false))) { // false = 無 BOM
                    sw.Write(rTB_Display.Text);
                }
                MessageBox.Show("儲存成功");
            } catch (Exception ex) {
                MessageBox.Show("寫入失敗: " + ex.Message);
            }
        }
    }
}

關鍵改進點 (對比原碼)

原碼問題改進做法
手動 Close() 易漏釋資源採 using 區塊確保 Dispose() 自動釋放
編碼寫死 GB2312讀取端保留相容;寫入端建議預設 UTF8Encoding(false) (無 BOM)
Flush() 呼叫時機混亂using 結束自動 Flush/Close,無需手動干預
例外吞沒 catch { }記錄 ex.Message 利於除錯
字串拼接 += 效能差大量行建議 StringBuilder 或 File.ReadAllLines

現代簡潔寫法 (.NET Core / 5+)

// 一次性讀取所有行 (自動偵測編碼較難,建議明確指定)
var lines = File.ReadAllLines(path, Encoding.GetEncoding("GB2312"));
textBox.Text = string.Join(Environment.NewLine, lines);

// 一次性寫入
File.WriteAllText(path, textBox.Text, new UTF8Encoding(false));

編碼選擇建議

  • UTF-8 (無 BOM):跨平台、Web、新專案首選。
  • UTF-8 (有 BOM):Windows 記事本舊版相容性較好。
  • GB2312/Big5:僅限舊系統中文資料相容。
copyright © 萬盛學電腦網 all rights reserved