How to get only file names in a directory using C #?

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

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

I would like to know if there is a way to get the file names in strings, not whole paths.

+69
c #
Aug 21 '11 at 18:08
source share
7 answers

You can use Path.GetFileName to get the file name 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 is 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; } 
+143
Aug 21 '11 at 18:09
source share

You can use the Path.GetFileName(yourFileName); method Path.GetFileName(yourFileName); (MSDN) to just get the file name.

+7
Aug 21 '11 at 18:12
source share

You can use the DirectoryInfo and FileInfo classes.

 //GetFiles on DirectoryInfo returns a FileInfo object. var pdfFiles = new DirectoryInfo("C:\\Documents").GetFiles("*.pdf"); //FileInfo has a Name property that only contains the filename part. var firstPdfFilename = pdfFiles[0].Name; 
+6
Aug 21 '11 at 19:10
source share

There are so many ways :)

First way:

 string[] folders = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly); string jsonString = JsonConvert.SerializeObject(folders); 

The second way:

 string[] folders = new DirectoryInfo(yourPath).GetDirectories().Select(d => d.Name).ToArray(); 

The third way:

 string[] folders = new DirectoryInfo(yourPath).GetDirectories().Select(delegate(DirectoryInfo di) { return di.Name; }).ToArray(); 
0
Sep 12 '13 at 11:19 on
source share
 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GetNameOfFiles { public class Program { static void Main(string[] args) { string[] fileArray = Directory.GetFiles(@"YOUR PATH"); for (int i = 0; i < fileArray.Length; i++) { Console.WriteLine(fileArray[i]); } Console.ReadLine(); } } } 
0
Sep 24 '15 at 6:06
source share

You can just use linq

 Directory.EnumerateFiles(LoanFolder).Select(file => Path.GetFileName(file)); 

Note: EnumeratesFiles are more efficient than Directory.GetFiles, since you can start enumerating a collection of names before the entire collection is returned.

0
May 22 '19 at 23:10
source share
 string[] fileEntries = Directory.GetFiles(directoryPath); foreach (var file_name in fileEntries){ string fileName = file_name.Substring(directoryPath.Length + 1); Console.WriteLine(fileName); } 
0
Aug 26 '19 at 13:18
source share



All Articles