// 寫入 (覆蓋)
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("第一行");
sw.WriteLine("第二行");
}
// 追加
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("追加行");
}
// 讀取全部行
string[] lines = File.ReadAllLines(path, Encoding.GetEncoding("utf-8"));
// 逐行讀取 (大檔案)
using (StreamReader sr = new StreamReader(path, Encoding.GetEncoding("utf-8")))
{
string line;
while ((line = sr.ReadLine()) != null) { /* 處理 */ }
}
讀取中文文字檔出現亂碼,需指定正確編碼:
// 繁體中文常用 Big5,簡體常用 GB2312/UTF-8
using (StreamReader sr = new StreamReader(path, Encoding.GetEncoding("gb2312"))) { ... }
using (StreamReader sr = new StreamReader(path, Encoding.UTF8)) { ... }
| 操作 | 方法 | 範例 |
|---|---|---|
| 複製 | File.Copy | File.Copy(src, dest, true); // true=覆蓋 |
| 移動/重命名 | File.Move | File.Move(oldPath, newPath); |
| 刪除 | File.Delete | File.Delete(path); |
| 存在檢查 | File.Exists | if (File.Exists(path)) ... |
| 取得資訊 | FileInfo | new FileInfo(path).Length / CreationTime |
| 建立目錄 | Directory.CreateDirectory | Directory.CreateDirectory(@"C:\Data\Sub"); |
| 刪除目錄 | Directory.Delete | Directory.Delete(path, true); // true=遞迴 |
| 列舉檔案 | Directory.GetFiles | Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories); |
string full = Path.Combine(baseDir, "sub", "file.txt"); // 跨平台安全
string dir = Path.GetDirectoryName(full);
string name = Path.GetFileNameWithoutExtension(full);
string ext = Path.GetExtension(full);
string temp = Path.GetTempFileName(); // 唯一暫存檔
// 寫入位元組陣列
File.WriteAllBytes(path, byteArray);
// 讀取位元組陣列
byte[] data = File.ReadAllBytes(path);
// 串流式處理大檔案
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (BinaryReader br = new BinaryReader(fs))
{
int value = br.ReadInt32();
// ...
}
using 確保釋放;若需共享讀取,開啟時指定 FileShare.Read。\\?\ 前綴。ReadAllTextAsync、CopyToAsync 避免阻塞 UI 執行緒。