Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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.GetFiles("C:\\Documents", "*.pdf"); 

I would like to know if there is a way to only retrieve the file names in the strings rather than the entire paths.

like image 851
HelloWorld_Always Avatar asked Aug 21 '11 18:08

HelloWorld_Always


People also ask

How to get FileName in directory in c#?

The Directory. GetFiles() method in C# gets the names of all the files inside a specific directory. The Directory. GetFiles() method returns an array of strings that contains the absolute paths of all the files inside the directory specified in the method parameters.


2 Answers

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; } 
like image 84
Thomas Levesque Avatar answered Oct 19 '22 17:10

Thomas Levesque


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

like image 20
Abbas Avatar answered Oct 19 '22 16:10

Abbas