.NET Framework 提供 System.IO.File(靜態方法)與 System.IO.FileInfo(實例方法)兩個類別處理檔案操作,以及 Directory / DirectoryInfo 處理目錄操作。本文透過實際程式碼範例,詳細說明最常用的檔案開啟、建立、刪除等核心操作。
using System.IO;
File.Openpublic static FileStream Open(string path, FileMode mode)
範例:以附加模式開啟檔案並寫入位元組陣列
private void OpenFile()
{
FileStream fs = File.Open(@"c:\tempuploads\newFile.txt", FileMode.Append);
byte[] info = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' };
fs.Write(info, 0, info.Length);
fs.Close(); // 必須關閉釋放鎖定
}
File.Createpublic static FileStream Create(string path)
範例:建立檔案並立即關閉
private void MakeFile()
{
FileStream fs = File.Create(@"c:\tempuploads\newFile.txt");
fs.Close(); // Create 預設授予全存取權限,必須關閉才能被其他程式開啟
}
File.Deletepublic static void Delete(string path)
範例:刪除指定檔案
private void DeleteFile()
{
File.Delete(@"c:\tempuploads\newFile.txt");
}
FileMode 列舉值| 值 | 行為 |
|---|---|
CreateNew | 建立新檔,若存在則拋出例外 |
Create | 建立新檔,若存在則覆蓋 |
Open | 開啟現有檔案,不存在則拋出例外 |
OpenOrCreate | 開啟現有檔案,不存在則建立 |
Append | 開啟現有檔案並移至末尾,不存在則建立 |
最佳實務:建議搭配 using 區塊自動處理資源釋放,避免檔案鎖定問題:
using (FileStream fs = File.Open(path, FileMode.Append))
{
fs.Write(data, 0, data.Length);
} // 自動呼叫 Dispose() 關閉串流