Directory.GetFiles: how to get only the file name and not the full path?

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

Using C #, I want to get a list of files in a folder.
My goal: ["file1.txt", "file2.txt"]

So I wrote this:

 string[] files = Directory.GetFiles(dir); 

Unfortunately, I get this output: ["C:\\dir\\file1.txt", "C:\\dir\\file2.txt"]

After that, I could remove the unnecessary part of "C: \ dir \", but is there a more elegant solution?

+42
c # filepath
Sep 21 '12 at 4:45
source share
4 answers

You can use System.IO.Path.GetFileName for this.

eg.

 string[] files = Directory.GetFiles(dir); foreach(string file in files) Console.WriteLine(Path.GetFileName(file)); 

While you can use FileInfo , it is much harder than the approach you are already using (just extracting file paths). Therefore, I suggest you stick with GetFiles if you do not need additional functions of the FileInfo class.

+105
Sep 21
source share

Try

  string[] files = new DirectoryInfo(dir).GetFiles().Select(o => o.Name).ToArray(); 

An UnauthorizedAccessException may be thrown above the line. To process this link below the link

C # Handle System.UnauthorizedAccessException in LINQ

+18
Sep 21
source share

Look at using the FileInfo.Name Property

something like

 string[] files = Directory.GetFiles(dir); for (int iFile = 0; iFile < files.Length; iFile++) string fn = new FileInfo(files[iFile]).Name; 

Also consider using DirectoryInfo Class and FileInfo Class

+7
Sep 21
source share

Use this to get only the file name.

 Path.GetFileName(files[0]); 
+2
Sep 21
source share



All Articles