.NET 透過 System.IO 命名空間提供檔案 I/O 功能。基礎抽象為 Stream (位元組串流),上層封裝 StreamReader/StreamWriter 處理文字編碼轉換,支援 FileStream (檔案) 與 MemoryStream (記憶體) 等多種後端。
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 |
// 一次性讀取所有行 (自動偵測編碼較難,建議明確指定)
var lines = File.ReadAllLines(path, Encoding.GetEncoding("GB2312"));
textBox.Text = string.Join(Environment.NewLine, lines);
// 一次性寫入
File.WriteAllText(path, textBox.Text, new UTF8Encoding(false));