c#怎么獲取路徑中的文件名

c#
小億
533
2024-03-18 20:04:38

要獲取路徑中的文件名,可以使用System.IO.Path類中的GetFileName方法。示例如下:

using System;

class Program
{
    static void Main()
    {
        string path = @"C:\Users\Username\Documents\example.txt";
        string fileName = System.IO.Path.GetFileName(path);
        
        Console.WriteLine(fileName); // 輸出 example.txt
    }
}

上面的代碼中,我們定義了一個(gè)路徑字符串path,然后使用Path.GetFileName方法獲取路徑中的文件名,并將其存儲(chǔ)在fileName變量中。最后,我們通過(guò)Console.WriteLine輸出文件名。

0