Bài tập - Đọc và ghi vào tệp
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
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
Ở phía trên cùng của
Program.cs, hãy thêmusing Newtonsoft.Json:using Newtonsoft.Json;Trong
Program.cstrực tiếp bên dưới phương phápFindFiles, hãy thêm mộtrecordmô hình dữ sales.json dữ liệu:record SalesData (double Total);
Tạo phương pháp tính tổng doanh thu
Trong
Program.cs, ngay trước đườngrecordbạ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ấtIEnumerable<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; }Trong phương pháp đó, thay thế
// READ FILES LOOPbằng một vòng lặp lặp trênsalesFiles, đọc tệp, phân tích nội dung dưới dạng JSON, rồi tăng biếnsalesTotalvới giá trịtotaltừ 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
Trong tệp
Program.cs, hãy thêm cuộc gọi vào hàmCalculateSalesTotalngay phía trên cuộcFile.WriteAllTextgọ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
Trong tệp
Program.cs, sửa đổi khốiFile.WriteAllTextđể ghi giá trị của biếnsalesTotalvào tệp totals.txt của bạn. Khi bạn đang ở đó, hãy thay đổiFile.WriteAllTextgọi thànhFile.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}");Lưu tệp Program.cs bằng cách nhấn Ctrl+S / Cmd+S.
Chạy chương trình
Chạy chương trình từ thiết bị đầu cuối:
dotnet runKhô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.
Chạy lại chương trình từ thiết bị đầu cuối.
dotnet runChọ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);