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

Chương trình C# tách các phần trong đường dẫn Windows

Sử dụng String.Split('\\') để tách đường dẫn theo dấu backslash. Lưu ý escape backslash trong chuỗi verbatim @\"...\".

Ví dụ

using System;

class Program
{
    static void Main()
    {
        string str = @"D:\Downloads\Amit";
        Console.WriteLine("Thư mục...\n" + str);
        string[] myStr = str.Split('\\');
        Console.WriteLine("\nTách...");
        foreach (string ch in myStr)
            Console.WriteLine(ch);
    }
}

Kết quả

Thư mục...
D:\Downloads\Amit
Tách...
D:
Downloads
Amit

Mẹo: Dùng Path.GetDirectoryName, Path.GetFileName cho thao tác đường dẫn chuẩn hơn.