Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Các phương thức Path trong C#

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ứcMô tảVí dụ inputKết quả
GetExtensionLấy phần mở rộngD:\file.txt.txt
GetFileNameLấy tên file + mở rộngD:\file.txtfile.txt
GetFileNameWithoutExtensionLấy tên file không mở rộngD:\file.txtfile
GetDirectoryNameLấy thư mục chaD:\file.txtD:\
GetFullPathChuẩn hóa đường dẫn tuyệt đối..\file.txtC:\Project\file.txt
CombineGhép đường dẫn an toàn("D:", "folder", "file.txt")D:\folder\file.txt
ChangeExtensionThay đổi phần mở rộng("file.txt", ".bak")file.bak
GetTempFileNameTạo file tạm duy nhất-C:\Temp\tmp123.tmp
GetRandomFileNameTạ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";