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

C# 檔案操作實用技巧大全

     編輯:關於C#

文字檔讀寫


// 寫入 (覆蓋)
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.CopyFile.Copy(src, dest, true); // true=覆蓋
移動/重命名File.MoveFile.Move(oldPath, newPath);
刪除File.DeleteFile.Delete(path);
存在檢查File.Existsif (File.Exists(path)) ...
取得資訊FileInfonew FileInfo(path).Length / CreationTime
建立目錄Directory.CreateDirectoryDirectory.CreateDirectory(@"C:\Data\Sub");
刪除目錄Directory.DeleteDirectory.Delete(path, true); // true=遞迴
列舉檔案Directory.GetFilesDirectory.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。
  • 路徑過長 (>260字元):啟用長路徑支援 (Windows 10 1607+ / .NET Core 2.1+),或使用 \\?\ 前綴。
  • 非同步 I/O:.NET 4.5+ 使用 ReadAllTextAsync、CopyToAsync 避免阻塞 UI 執行緒。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved