Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# แยกส่วนในไดเรกทอรี Windows

ใช้ String.Split('\\') แยกพาธไฟล์ Windows ตาม Backslash (ต้อง Escape เป็น '\\\\' หรือใช้ Verbatim String @)

ตัวอย่างโค้ด

using System;

class Program
{
    static void Main()
    {
        string str = @"D:\Downloads\Amit";
        Console.WriteLine("Directory...\n" + str);
        
        string[] myStr = str.Split('\\');
        Console.WriteLine("\nSplit...");
        foreach (string ch in myStr) Console.WriteLine(ch);
    }
}

ผลลัพธ์

Directory...
D:\Downloads\Amit
Split...
D:
Downloads
Amit

แนะนำ: ใช้ Path.GetDirectoryName, Path.GetFileName แทน เพราะ Cross-platform และจัดการ Edge Cases ได้ดีกว่า