
- C# 基礎教程
- C# - 首頁
- C# - 概述
- C# - 環境
- C# - 程式結構
- C# - 基本語法
- C# - 資料型別
- C# - 型別轉換
- C# - 變數
- C# - 常量
- C# - 運算子
- C# - 決策制定
- C# - 迴圈
- C# - 封裝
- C# - 方法
- C# - 可空型別
- C# - 陣列
- C# - 字串
- C# - 結構體
- C# - 列舉
- C# - 類
- C# - 繼承
- C# - 多型
- C# - 運算子過載
- C# - 介面
- C# - 名稱空間
- C# - 預處理器指令
- C# - 正則表示式
- C# - 異常處理
- C# - 檔案 I/O
C# - Windows 檔案系統
C# 允許您使用各種與目錄和檔案相關的類(例如DirectoryInfo 類和FileInfo 類)來處理目錄和檔案。
DirectoryInfo 類
DirectoryInfo 類派生自FileSystemInfo 類。它具有用於建立、移動和瀏覽目錄和子目錄的各種方法。此類不能被繼承。
以下是DirectoryInfo 類的一些常用屬性:
序號 | 屬性和描述 |
---|---|
1 | Attributes 獲取當前檔案或目錄的屬性。 |
2 | CreationTime 獲取當前檔案或目錄的建立時間。 |
3 | Exists 獲取一個布林值,指示目錄是否存在。 |
4 | Extension 獲取表示副檔名的字串。 |
5 | FullName 獲取目錄或檔案的完整路徑。 |
6 | LastAccessTime 獲取上次訪問當前檔案或目錄的時間。 |
7 | Name 獲取此 DirectoryInfo 例項的名稱。 |
以下是DirectoryInfo 類的一些常用方法:
序號 | 方法和描述 |
---|---|
1 | public void Create() 建立一個目錄。 |
2 | public DirectoryInfo CreateSubdirectory(string path) 在指定的路徑上建立子目錄或子目錄。指定的路徑可以相對於此 DirectoryInfo 類的例項。 |
3 | public override void Delete() 如果此 DirectoryInfo 為空,則將其刪除。 |
4 | public DirectoryInfo[] GetDirectories() 返回當前目錄的子目錄。 |
5 | public FileInfo[] GetFiles() 從當前目錄返回檔案列表。 |
有關屬性和方法的完整列表,請訪問 Microsoft 的 C# 文件。
FileInfo 類
FileInfo 類派生自FileSystemInfo 類。它具有用於建立、複製、刪除、移動和開啟檔案的屬性和例項方法,並有助於建立 FileStream 物件。此類不能被繼承。
以下是FileInfo 類的一些常用屬性:
序號 | 屬性和描述 |
---|---|
1 | Attributes 獲取當前檔案的屬性。 |
2 | CreationTime 獲取當前檔案的建立時間。 |
3 | Directory 獲取檔案所屬目錄的例項。 |
4 | Exists 獲取一個布林值,指示檔案是否存在。 |
5 | Extension 獲取表示副檔名的字串。 |
6 | FullName 獲取檔案的完整路徑。 |
7 | LastAccessTime 獲取上次訪問當前檔案的時間。 |
8 | LastWriteTime 獲取檔案的最後寫入活動時間。 |
9 | Length 獲取當前檔案的位元組大小。 |
10 | Name 獲取檔案的名稱。 |
以下是FileInfo 類的一些常用方法:
序號 | 方法和描述 |
---|---|
1 | public StreamWriter AppendText() 建立一個 StreamWriter,將文字附加到此 FileInfo 例項表示的檔案。 |
2 | public FileStream Create() 建立一個檔案。 |
3 | public override void Delete() 永久刪除檔案。 |
4 | public void MoveTo(string destFileName) 將指定的檔案移動到新位置,可以選擇指定新的檔名。 |
5 | public FileStream Open(FileMode mode) 以指定的模式開啟檔案。 |
6 | public FileStream Open(FileMode mode, FileAccess access) 以指定的模式和讀、寫或讀/寫訪問許可權開啟檔案。 |
7 | public FileStream Open(FileMode mode, FileAccess access, FileShare share) 以指定的模式、讀、寫或讀/寫訪問許可權以及指定的共享選項開啟檔案。 |
8 | public FileStream OpenRead() 建立一個只讀 FileStream。 |
9 | public FileStream OpenWrite() 建立一個只寫 FileStream。 |
有關屬性和方法的完整列表,請訪問 Microsoft 的 C# 文件。
示例
以下示例演示了上述類的用法:
using System; using System.IO; namespace WindowsFileApplication { class Program { static void Main(string[] args) { //creating a DirectoryInfo object DirectoryInfo mydir = new DirectoryInfo(@"c:\Windows"); // getting the files in the directory, their names and size FileInfo [] f = mydir.GetFiles(); foreach (FileInfo file in f) { Console.WriteLine("File Name: {0} Size: {1}", file.Name, file.Length); } Console.ReadKey(); } } }
編譯並執行程式後,它將顯示 Windows 目錄中檔案的名稱及其相應的大小。