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

.NET System.IO 檔案與目錄操作完整指南

     編輯:ASP.NET 基礎

核心類別概覽

類別特性適用場景
File靜態方法單次檔案建立/複製/移動/刪除/開啟串流
FileInfo實例方法對同一檔案多次操作、取得屬性資訊
Directory靜態方法單次目錄操作
DirectoryInfo實例方法列舉子目錄/檔案、多次操作同目錄
DriveInfo實例 (靜態取得)取得磁碟機資訊 (類型、容量、剩餘空間)
FileSystemWatcher事件導向即時監控檔案/目錄變更
Path靜態方法路徑字串操作 (合併、取副檔名、取隨機檔名…)

DriveInfo:取得磁碟資訊

foreach (var drive in DriveInfo.GetDrives()) {
    if (drive.IsReady) {
        Console.WriteLine($"類型:{drive.DriveType} 卷標:{drive.VolumeLabel} " +
                          $"{drive.Name} 總計:{drive.TotalSize/1e9:F1}GB 剩餘:{drive.TotalFreeSpace/1e9:F1}GB");
    } else {
        Console.WriteLine($"{drive.DriveType} 未就緒 (可能無媒體)");
    }
}

⚠ 必須先檢查 IsReady,否則存取 TotalSize 等屬性會擲出例外。

FileSystemWatcher:即時監控目錄變更

var watcher = new FileSystemWatcher(@"D:\watch", "*.*");
watcher.Changed += (s, e) => Console.WriteLine($"Changed: {e.FullPath}");
watcher.Created += (s, e) => Console.WriteLine($"Created: {e.FullPath}");
watcher.Deleted += (s, e) => Console.WriteLine($"Deleted: {e.FullPath}");
watcher.Error   += (s, e) => Console.WriteLine($"Error: {e.GetException()}");
watcher.EnableRaisingEvents = true; // 必須設為 true 才啟動
Console.WriteLine("監控中... 按任意鍵結束"); Console.ReadKey();

常用過濾:watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;

Path 常用靜態方法

Path.GetDirectoryName(@"d:\abc")       // "d:\"
Path.GetDirectoryName(@"d:\abc\")       // "d:\abc" (尾斜線影響結果)
Path.GetFileNameWithoutExtension(@"d:\abc.txt") // "abc"
Path.GetRandomFileName()               // "abc123.tmp" (加密隨機)
Path.Combine(@"d:\folder", "file.txt") // "d:\folder\file.txt"
Path.GetInvalidPathChars()             // 陣列:不可用於路徑的字元
Path.GetInvalidFileNameChars()         // 陣列:不可用於檔名的字元

跨平台注意

上述類別底層呼叫 Windows API,**僅限 Windows 環境**。.NET Core / .NET 5+ 跨平台專案請改用 System.IO.Abstractions 或直接使用 File/Directory (已支援 Linux/macOS),但 DriveInfo、FileSystemWatcher 行為在非 Windows 平台可能不同。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved