How to get only filenames within a directory using c#?

后端 未结 7 1723
闹比i
闹比i 2020-12-04 15:05

When I use the line of code as below , I get an string array containing the entire path of the individual files .

private string[] pdfFiles = Directory.GetF         


        
7条回答
  •  余生分开走
    2020-12-04 15:34

    You can use Path.GetFileName to get the filename from the full path

    private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf")
                                         .Select(Path.GetFileName)
                                         .ToArray();
    

    EDIT: the solution above uses LINQ, so it requires .NET 3.5 at least. Here's a solution that works on earlier versions:

    private string[] pdfFiles = GetFileNames("C:\\Documents", "*.pdf");
    
    private static string[] GetFileNames(string path, string filter)
    {
        string[] files = Directory.GetFiles(path, filter);
        for(int i = 0; i < files.Length; i++)
            files[i] = Path.GetFileName(files[i]);
        return files;
    }
    

提交回复
热议问题