Bài tập - Đọc và ghi vào tệp

Đã hoàn thành

Bạn cũng có thể sử dụng lớp File trong .NET để ghi dữ liệu vào tệp và đọc dữ liệu từ tệp.

Bạn sắp hoàn tất việc tạo kiệt tác .NET cho Tailwind Traders. Cho đến nay, mã của bạn sẽ đọc bất kỳ thư mục nào, tìm tất cả .json và tạo một tệp totals.txt bạn.

Trong bài tập này, bạn hoàn thành dự án bằng cách đọc tệp .json, thêm tổng cửa hàng và viết tổng cuối vào tệp totals.txt lưu trữ.

Thêm Newtonsoft.Json vào dự án

  1. Sử dụng thiết bị đầu cuối, thêm Newtonsoft.Json vào dự án.

    dotnet add package Newtonsoft.Json
    

Chuẩn bị cho dữ liệu bán hàng

  1. Ở phía trên cùng của Program.cs, hãy thêm using Newtonsoft.Json:

    using Newtonsoft.Json;
    
  2. Trong Program.cs trực tiếp bên dưới phương pháp FindFiles, hãy thêm một record mô hình dữ sales.json dữ liệu:

    record SalesData (double Total);
    

Tạo phương pháp tính tổng doanh thu

  1. Trong Program.cs, ngay trước đường record bạn đã thêm ở bước trước đó, hãy tạo một hàm mới để tính tổng doanh thu. Phương pháp này sẽ mất IEnumerable<string> đường dẫn tệp mà nó có thể lặp lại.

    double CalculateSalesTotal(IEnumerable<string> salesFiles)
    {
        double salesTotal = 0;
    
        // READ FILES LOOP
    
        return salesTotal;
    }
    
  2. Trong phương pháp đó, thay thế // READ FILES LOOP bằng một vòng lặp lặp trên salesFiles, đọc tệp, phân tích nội dung dưới dạng JSON, rồi tăng biến salesTotal với giá trị total từ tệp:

    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;
    }
    

Gọi phương thức CalculateSalesTotals

  1. Trong tệp Program.cs, hãy thêm cuộc gọi vào hàm CalculateSalesTotal ngay phía trên cuộc File.WriteAllText gọi:

    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);
    

Viết tổng cộng vào tệp totals.txt này

  1. Trong tệp Program.cs, sửa đổi khối File.WriteAllText để ghi giá trị của biến salesTotal vào tệp totals.txt của bạn. Khi bạn đang ở đó, hãy thay đổi File.WriteAllText gọi thành File.AppendAllText để không có nội dung nào trong tệp bị ghi đè.

    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. Lưu tệp Program.cs bằng cách nhấn Ctrl+S / Cmd+S.

Chạy chương trình

  1. Chạy chương trình từ thiết bị đầu cuối:

    dotnet run
    

    Không có đầu ra từ chương trình. Nếu bạn tìm trong tệp salesTotalDir/totals.txt, bạn sẽ tìm thấy tổng doanh thu từ tệp sales.json hàng.

  2. Chạy lại chương trình từ thiết bị đầu cuối.

    dotnet run
    
  3. Chọn tệp salesTotalDir/totals.txt hàng.

    Tệp totals.txt hiện có dòng thứ hai. Mỗi lần bạn chạy chương trình, tổng sẽ được cộng lại và dòng mới sẽ được ghi vào tệp.

Công việc xuất sắc! Bạn đã viết một công cụ thông minh, mạnh mẽ và tiện dụng mà Tailwind Traders có thể sử dụng để xử lý tất cả các cửa hàng bán hàng của mình mỗi đêm. Trong bài học tiếp theo, chúng tôi sẽ xem xét những gì bạn đã học được và một vài mẹo để nhớ.

Bạn gặp sự cố?

Nếu bạn bị kẹt trong bài tập này, dưới đây là mã đầy đủ cho dự án này:

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);