練習 - 使用檔案系統

已完成

您可使用 .NET 來尋找及傳回檔案與資料夾的相關資訊。

Tailwind Traders 在世界各地有許多實體存放區。 每天晚上,每個商店都會建立名為 sales.json 的檔案,其中包含當天所有銷售的總計。 這些檔案會依儲存識別碼命名的資料夾進行分類。

注意

本課程模組使用 .NET CLI (命令列介面)Visual Studio Code 進行本機開發。 完成本課程模組之後,您可以使用 Visual Studio (Windows) 或 Visual Studio for Mac (macOS) 等開發環境來套用您學到的概念,或在 Visual Studio Code (Windows、Linux 和 macOS) 中繼續開發。

本課程模組使用 .NET 6.0 SDK。 確認您已在慣用終端中執行下列命令來安裝 .NET 6.0:

dotnet --list-sdks

您會看到類似以下的輸出:

3.1.100 [C:\program files\dotnet\sdk]
5.0.100 [C:\program files\dotnet\sdk]
6.0.100 [C:\program files\dotnet\sdk]

確定已列出開頭為 6 的版本。 如果未列出任何項目或找不到命令,則請安裝最新的 .NET 6.0 SDK

複製專案

在本練習中,您會撰寫 .NET 程式,用來在目錄及其子目錄中搜尋名為 sales.json 的檔案。

系統已為您建立入門專案。 您會在 Visual Studio Code 中使用整合式終端機加以複製。

  1. 打開 Visual Studio Code。

  2. 在主功能表中,選取 [檢視] 再選 [終端機] 來開啟 [終端機] 視窗。

  3. (選擇性) 在 [終端機] 視窗中,切換至您要將檔案複製到哪個目錄,例如 c:\MyProjects

  4. 在 [終端機] 視窗中,執行下列命令以複製入門專案,並移至複製的專案:

    git clone https://github.com/MicrosoftDocs/mslearn-dotnet-files && cd mslearn-dotnet-files
    
  5. 執行下列命令,建立新的 .NET 主控台專案:

    dotnet new console -f net6.0 -n mslearn-dotnet-files -o .
    
  6. 執行下列命令,在相同的 Visual Studio Code 執行個體中開啟新的 .NET 專案:

    code -a .
    

    提示

    此時 Visual Studio Code 可能會提示您缺少建置和執行專案所需的資產。

    Screenshot showing the Visual Studio prompt that lets the user know something is missing from the project.

    選取含有驚嘆號的三角形,然後選取 [重新啟動終端機],以新增讓 Visual Studio Code 執行專案並加以偵錯的檔案。

  7. 在 [檔案總管] 視窗的 mslearn-dotnet-files 底下,展開 stores 資料夾和其中的每個編號資料夾。

    Screenshot of EXPLORER window that shows the project folder structure.

尋找 sales.json 檔案

下列工作會建立一個程式,在 mslearn-dotnet-files 專案的所有資料夾中尋找所有的 sales.json 檔案。

包含 System.IO 命名空間

  1. 在 [檔案總管] 視窗中選取 Program.cs 檔案,在編輯器中開啟。

    Screenshot of the Explorer window highlighting the program.cs file.

  2. 將下列程式碼貼到 Program.cs 檔案的第一行,以匯入 System.IOSystem.Collections.Generic 命名空間:

    using System.IO;
    using System.Collections.Generic;
    

注意

從 .NET 6 開始,上述程式碼中的兩個陳述式會依據 ImplcitUsings 屬性群組的方式自動包含在新專案中。 由於我們在建立新的主控台專案時指定了 -f net6.0 旗標,因此會以隱含方式新增。 不過,如果您使用較舊的專案,則必須將其包含在 Program.cs 檔案中,如果您將其保留在該檔案中,此專案就不受影響。

撰寫函式來尋找 sales.json 檔案

建立稱為 FindFiles 且接受 folderName 參數的新函式。

  1. Console.WriteLine("Hello, World!"); 一行取代為下列程式碼:

    IEnumerable<string> FindFiles(string folderName)
    {
        List<string> salesFiles = new List<string>();
    
        var foundFiles = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories);
    
        foreach (var file in foundFiles)
        {
            // The file name will contain the full path, so only check the end of it
            if (file.EndsWith("sales.json"))
            {
                salesFiles.Add(file);
            }
        }
    
        return salesFiles;
    }
    
  2. using 陳述式下方插入下列程式碼來呼叫 FindFiles 函式。 此程式碼會傳入 stores 資料夾名稱作為搜尋檔案的位置。

    var salesFiles = FindFiles("stores");
    
    foreach (var file in salesFiles)
    {
        Console.WriteLine(file);
    }
    
  3. Ctrl+S (macOS 請按 Cmd+S) 儲存 Program.cs 檔案。

執行程式

  1. 在終端機視窗中輸入下列命令,執行程式:

    dotnet run
    
  2. 該程式應該會顯示下列輸出:

    stores/sales.json
    stores/201/sales.json
    stores/202/sales.json
    stores/203/sales.json
    stores/204/sales.json
    

非常好! 您已成功撰寫一個命令列程式,該程式會周遊 stores 目錄中的所有資料夾,並列出所有找到的 sales.json 檔案。

在此範例中,stores 目錄的路徑很簡單,且是在程式的工作目錄中。 在下一個單元中,您將了解如何使用 Path 類別來建構能跨作業系統運作的複雜結構。

遇到問題了嗎?

如果您在執行程式時遇到任何問題,以下是 Program.cs 檔案已完成的程式碼。 請將 Program.cs 檔案的內容取代為下列程式碼:

var salesFiles = FindFiles("stores");
    
foreach (var file in salesFiles)
{
    Console.WriteLine(file);
}

IEnumerable<string> FindFiles(string folderName)
{
    List<string> salesFiles = new List<string>();

    var foundFiles = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories);

    foreach (var file in foundFiles)
    {
        // The file name will contain the full path, so only check the end of it
        if (file.EndsWith("sales.json"))
        {
            salesFiles.Add(file);
        }
    }

    return salesFiles;
}