練習 - 讀取及寫入檔案

已完成

您也可以使用 .NET 中的 File 類別,將資料寫入檔案或從檔案讀取資料。

您只差一步就能夠為 Tailwind Traders 完成這件 .NET 的傑作了。 到目前為止,您的程式碼能讀取任何目錄、尋找所有 .json 檔案,並建立 totals.txt 檔案。

在此練習中,您會讀取 .json 檔案、計算商店總額,並將總計寫入 totals.txt 檔案來完成專案。

將 Json.NET 新增至專案

  1. 使用終端機將 Json.NET 新增至專案。

    dotnet add package Newtonsoft.Json
    

準備銷售資料

  1. Program.cs 的頂端,新增 using Newtonsoft.Json

    using Newtonsoft.Json;
    
  2. Program.csFindFiles 方法正下方,新增將會建立 sales. json 資料模型的新 record

    record SalesData (double Total);
    

建立計算銷售總額的方法

  1. Program.cs 中,在您於上一個步驟中新增的 record 行之前,建立新的函數以計算銷售總額。 這個方法應該會包含可供逐一查看的檔案路徑 IEnumerable<string>

    double CalculateSalesTotal(IEnumerable<string> salesFiles)
    {
        double salesTotal = 0;
    
        // READ FILES LOOP
    
        return salesTotal;
    }
    
  2. 在此方法中,使用逐一查看 salesFiles 的迴圈取代 // READ FILES LOOP、讀取檔案、將內容剖析為 JSON,然後使用檔案中的 total 值累加 salesTotal 變數:

    double CalculateSalesTotal(IEnumerable<string> salesFiles)
    {
        double salesTotal = 0;
    
        // Loop over each file path in salesFiles
        foreach (var file in salesFiles)
        {      
            // Read the contents of the file
            string salesJson = File.ReadAllText(file);
    
            // Parse the contents as JSON
            SalesData? data = JsonConvert.DeserializeObject<SalesData?>(salesJson);
    
            // Add the amount found in the Total field to the salesTotal variable
            salesTotal += data?.Total ?? 0;
        }
    
        return salesTotal;
    }
    

呼叫 CalculateSalesTotals 方法

  1. Program.cs 檔案中,新增呼叫至 File.WriteAllText 呼叫正上方的 CalculateSalesTotal 函式:

    var currentDirectory = Directory.GetCurrentDirectory();
    var storesDir = Path.Combine(currentDirectory, "stores");
    
    var salesTotalDir = Path.Combine(currentDirectory, "salesTotalDir");
    Directory.CreateDirectory(salesTotalDir);
    
    var salesFiles = FindFiles(storesDir);
    
    var salesTotal = CalculateSalesTotal(salesFiles); // Add this line of code
    
    File.WriteAllText(Path.Combine(salesTotalDir, "totals.txt"), String.Empty);
    

將總計寫入 totals.txt 檔案

  1. Program.cs 檔案中,修改 File.WriteAllText 區塊,以將 salesTotal 變數的值寫入 totals.txt 檔案。 當在此時,請將 File.WriteAllText 呼叫變更為 File.AppendAllText,因此不會覆寫檔案中的任何內容。

    var currentDirectory = Directory.GetCurrentDirectory();            
    var storesDir = Path.Combine(currentDirectory, "stores");
    
    var salesTotalDir = Path.Combine(currentDirectory, "salesTotalDir");
    Directory.CreateDirectory(salesTotalDir);            
    
    var salesFiles = FindFiles(storesDir);
    
    var salesTotal = CalculateSalesTotal(salesFiles);
    
    File.AppendAllText(Path.Combine(salesTotalDir, "totals.txt"), $"{salesTotal}{Environment.NewLine}");
    
  2. Ctrl+S / Cmd+S 以儲存 Program.cs 檔案。

執行程式

  1. 從終端機執行程式:

    dotnet run
    

    程式並未顯示任何輸出。 如果查看 salesTotalDir/totals.txt 檔案,即會看到來自 sales.json 檔案的所有銷售總額。

  2. 再次從終端機執行程式。

    dotnet run
    
  3. 選取 salesTotalDir/totals.txt 檔案。

    totals.txt 檔案現在有第二行。 每次執行此程式時,總額都會再次加總,並將新行寫入檔案中。

做得好! 您已撰寫了一個強大且方便的智慧工具,Tailwind Traders 可在每天晚上使用這個工具來處理旗下所有商店的銷售。 在下一個單元中,我們將檢閱您所學到的內容與一些要記住的提示。

遇到問題了嗎?

如果在此練習中遇到問題,以下是此專案的完整程式碼:

using Newtonsoft.Json; 

var currentDirectory = Directory.GetCurrentDirectory();
var storesDirectory = Path.Combine(currentDirectory, "stores");

var salesTotalDir = Path.Combine(currentDirectory, "salesTotalDir");
Directory.CreateDirectory(salesTotalDir);   

var salesFiles = FindFiles(storesDirectory);

var salesTotal = CalculateSalesTotal(salesFiles);

File.AppendAllText(Path.Combine(salesTotalDir, "totals.txt"), $"{salesTotal}{Environment.NewLine}");

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

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

    foreach (var file in foundFiles)
    {
        var extension = Path.GetExtension(file);
        if (extension == ".json")
        {
            salesFiles.Add(file);
        }
    }

    return salesFiles;
}

double CalculateSalesTotal(IEnumerable<string> salesFiles)
{
    double salesTotal = 0;
    
    // Loop over each file path in salesFiles
    foreach (var file in salesFiles)
    {      
        // Read the contents of the file
        string salesJson = File.ReadAllText(file);
    
        // Parse the contents as JSON
        SalesData? data = JsonConvert.DeserializeObject<SalesData?>(salesJson);
    
        // Add the amount found in the Total field to the salesTotal variable
        salesTotal += data?.Total ?? 0;
    }
    
    return salesTotal;
}

record SalesData (double Total);