Đường dẫn và thư mục
Thuộc phần C# và .NET cơ bản trong hành trình ASP.NET Core của Coddy. Bài học 18 trên 20.
Đường dẫn cho biết tên tệp và các thư mục nằm phía trên tệp đó. Windows dùng \ để phân tách các phần, còn Linux và macOS dùng /, vì vậy hãy tạo đường dẫn bằng Path.Combine, phương thức này sẽ dùng dấu phân tách phù hợp. Đường dẫn tương đối như exports/a.csv bắt đầu từ thư mục hiện tại, tức thư mục mà chương trình chạy trong đó.
var folder = Path.Combine("backups", "2026");
Directory.CreateDirectory(folder);
var target = Path.Combine(folder, "photo.jpg");
Console.WriteLine(target);
Console.WriteLine(Path.GetExtension(target));
Console.WriteLine(Path.GetFileNameWithoutExtension(target));Trên Linux, đoạn code này in ra backups/2026/photo.jpg, .jpg và photo. Việc ghi vào thư mục không tồn tại sẽ gây ra ngoại lệ DirectoryNotFoundException. Directory.CreateDirectory tạo mọi thư mục còn thiếu trong đường dẫn và không làm gì nếu chúng đã tồn tại. File.WriteAllLines(path, lines) ghi mỗi chuỗi thành một dòng.
Thử thách
DễThêm lệnh export để ghi các khoản chi dưới dạng CSV, định dạng mà lệnh import đọc.
- Thêm
case "export":phía trêndefault:. Tạo thư mụcexports, rồi tạo đường dẫnexports/expenses.csvbằngPath.Combine. - Dùng
File.WriteAllLinesđể ghi một dòng cho mỗi khoản chi: tên, số tiền và danh mục, phân tách bằng dấu phẩy. Ghi số tiền bằngToString("F2", CultureInfo.InvariantCulture)để số tiền có hai chữ số thập phân và dấu chấm trên mọi máy tính:Lunch,12.50,food Train,4.20,travel Groceries,31.80,food - In
Exported 3 expenses to exports/expenses.csv.cùng số lượng và đường dẫn. - Thêm nhánh
help:help exportin raexport: writes every expense to exports/expenses.csv.
Thử nhé: terminal bên cạnh trình soạn thảo đã có lệnh dotnet run -- export, nên hãy nhấn Run: Exported 3 expenses to exports/expenses.csv. Terminal hiển thị nội dung chương trình in ra, chứ không hiển thị các tệp chương trình ghi, nên khi nhấn Check, chương trình sẽ mở tệp và kiểm tra ba dòng ở trên. Chương trình cũng xuất dữ liệu hai lần, vì vậy lần chạy thứ hai sẽ gặp một thư mục đã tồn tại.
Tự làm thử
using System.Globalization;
using System.Text.Json;
var file = "expenses.json";
var expenses = new List<Expense>();
if (File.Exists(file))
{
expenses = JsonSerializer.Deserialize<List<Expense>>(File.ReadAllText(file)) ?? new List<Expense>();
}
var budgets = new Dictionary<string, decimal>();
if (File.Exists("budgets.json"))
{
budgets = JsonSerializer.Deserialize<Dictionary<string, decimal>>(File.ReadAllText("budgets.json")) ?? new Dictionary<string, decimal>();
}
var count = expenses.Count;
var total = expenses.Sum(e => e.Amount);
if (args.Length == 0)
{
Console.WriteLine("Expense Tracker");
Console.WriteLine($"{count} expenses");
Console.WriteLine($"Total: {total:F2}");
}
else
{
switch (args[0])
{
case "add":
if (args.Length < 3)
{
Console.Error.WriteLine("Usage: add <name> <amount> [category]");
return 1;
}
if (!decimal.TryParse(args[2], CultureInfo.InvariantCulture, out var amount))
{
Console.Error.WriteLine($"Invalid amount: {args[2]}");
return 1;
}
if (amount is <= 0 or > 10000)
{
Console.Error.WriteLine("The amount must be more than 0 and at most 10000.");
return 1;
}
var category = args.Length > 3 ? args[3] : "other";
var expense = new Expense(args[1], amount, category);
expenses.Add(expense);
File.WriteAllText(file, JsonSerializer.Serialize(expenses));
Console.WriteLine($"Added {expense.Name}: {expense.Amount:F2} ({expense.Category})");
if (budgets.TryGetValue(category, out var limit))
{
var spent = expenses.Where(e => e.Category == category).Sum(e => e.Amount);
if (spent > limit)
{
Console.WriteLine($"Over budget for {category}: {spent:F2} of {limit:F2}");
}
}
break;
case "remove":
if (args.Length < 2)
{
Console.Error.WriteLine("Usage: remove <name>");
return 1;
}
Expense? match = expenses.Find(e => e.Name == args[1]);
if (match is null)
{
Console.Error.WriteLine($"No expense named {args[1]}.");
return 1;
}
expenses.Remove(match);
File.WriteAllText(file, JsonSerializer.Serialize(expenses));
Console.WriteLine($"Removed {match.Name}: {match.Amount:F2}");
break;
case "list":
var shown = args.Length > 1 ? expenses.Where(e => e.Category == args[1]).ToList() : expenses;
if (shown.Count == 0)
{
Console.WriteLine("No expenses.");
break;
}
foreach (var line in shown.Select(e => $"{e.Name}: {e.Amount:F2} ({e.Category})"))
{
Console.WriteLine(line);
}
break;
case "top":
var howMany = 3;
if (args.Length > 1 && !int.TryParse(args[1], out howMany))
{
Console.Error.WriteLine($"Invalid number: {args[1]}");
return 1;
}
var biggest = expenses.OrderByDescending(e => e.Amount).Take(howMany);
foreach (var line in biggest.Select((e, i) => $"{i + 1}. {e.Name}: {e.Amount:F2} ({e.Category})"))
{
Console.WriteLine(line);
}
break;
case "categories":
var groups = expenses.GroupBy(e => e.Category).OrderByDescending(g => g.Sum(e => e.Amount));
foreach (var g in groups)
{
Console.WriteLine($"{g.Key}: {g.Sum(e => e.Amount):F2} ({g.Count()})");
}
break;
case "help":
var topic = args.Length > 1 ? args[1] : "";
var help = topic switch
{
"" => "Type help <command>, such as help add.",
"add" => "add <name> <amount> [category]: saves an expense",
"remove" => "remove <name>: deletes the first expense with that name",
"list" => "list [category]: shows the saved expenses",
"top" => "top [n]: shows the n biggest expenses, 3 by default",
"categories" => "categories: shows the total of each category",
"import" => "import <file>: adds the expenses in a CSV file",
_ => $"No help for {topic}.",
};
Console.WriteLine(help);
break;
case "import":
if (args.Length < 2)
{
Console.Error.WriteLine("Usage: import <file>");
return 1;
}
if (!File.Exists(args[1]))
{
Console.Error.WriteLine($"No file named {args[1]}.");
return 1;
}
var imported = 0;
var lineNumber = 0;
foreach (var row in File.ReadAllLines(args[1]))
{
lineNumber++;
try
{
var parts = row.Split(',');
if (parts.Length != 3)
{
throw new FormatException("A line needs a name, an amount and a category.");
}
expenses.Add(new Expense(parts[0], decimal.Parse(parts[1], CultureInfo.InvariantCulture), parts[2]));
imported++;
}
catch (FormatException ex)
{
Console.Error.WriteLine($"Line {lineNumber} skipped: {ex.Message}");
}
}
File.WriteAllText(file, JsonSerializer.Serialize(expenses));
Console.WriteLine($"Imported {imported} expenses from {args[1]}.");
break;
default:
Console.Error.WriteLine($"Unknown command: {args[0]}");
return 1;
}
}
return 0;
Tất cả bài học trong C# và .NET cơ bản
1Chương trình đầu tiên của bạn
Xin chào, .NETVar và nội suy chuỗi