Lớp Path trong namespace System.IO cung cấp các phương thức tĩnh để thao tác đường dẫn file (path) an toàn, đa nền tảng, tránh xử lý chuỗi thủ công dễ sai.
Các phương thức phổ biến
| Phương thức | Mô tả | Ví dụ input | Kết quả |
|---|---|---|---|
GetExtension | Lấy phần mở rộng | D:\file.txt | .txt |
GetFileName | Lấy tên file + mở rộng | D:\file.txt | file.txt |
GetFileNameWithoutExtension | Lấy tên file không mở rộng | D:\file.txt | file |
GetDirectoryName | Lấy thư mục cha | D:\file.txt | D:\ |
GetFullPath | Chuẩn hóa đường dẫn tuyệt đối | ..\file.txt | C:\Project\file.txt |
Combine | Ghép đường dẫn an toàn | ("D:", "folder", "file.txt") | D:\folder\file.txt |
ChangeExtension | Thay đổi phần mở rộng | ("file.txt", ".bak") | file.bak |
GetTempFileName | Tạo file tạm duy nhất | - | C:\Temp\tmp123.tmp |
GetRandomFileName | Tạo tên file ngẫu nhiên | - | abc123.tmp |
Ví dụ minh họa
using System.IO;
using System;
class Program
{
static void Main()
{
string myPath = @"D:\one.txt";
string fileExtension = Path.GetExtension(myPath);
string fileName = Path.GetFileName(myPath);
string noExtension = Path.GetFileNameWithoutExtension(myPath);
Console.WriteLine("File Extension: " + fileExtension); // .txt
Console.WriteLine("File Name: " + fileName); // one.txt
Console.WriteLine("File Name without extension: " + noExtension); // one
}
}
Kết quả
File Extension: .txt
File Name: one.txt
File Name without extension: one
Lưu ý quan trọng
- Không kiểm tra tồn tại: Path chỉ thao tác chuỗi, không truy cập đĩa.
- Đa nền tảng: Tự động xử lý separator (\ trên Windows, / trên Linux/macOS).
- Path.Combine xử lý tự động separator - luôn ưu tiên dùng thay vì nối chuỗi.
- InvalidPathChars - kiểm tra ký tự không hợp lệ.
Ví dụ Path.Combine (Best Practice)
// ✅ Tốt - tự động xử lý separator
string path = Path.Combine(baseDir, "subfolder", "file.txt");
// ❌ Tránh - hardcode separator, dễ sai cross-platform
string path = baseDir + "\\subfolder\\file.txt";