Directory.GetFiles: how to get only filename, not full path?

C#FilepathGetfiles

C# Problem Overview


> Possible Duplicate:
> How to get only filenames within a directory using c#?

Using C#, I want to get the 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"]

I could strip the unwanted "C:\dir\" part afterward, but is there a more elegant solution?

C# Solutions


Solution 1 - C#

You can use System.IO.Path.GetFileName to do this.

E.g.,

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

While you could use FileInfo, it is much more heavyweight than the approach you are already using (just retrieving file paths). So I would suggest you stick with GetFiles unless you need the additional functionality of the FileInfo class.

Solution 2 - C#

Try,

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

Above line may throw UnauthorizedAccessException. To handle this check out below link

https://stackoverflow.com/questions/12373529/c-sharp-handle-system-unauthorizedaccessexception-in-linq

Solution 3 - C#

Have a look at using 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 have a look at using DirectoryInfo Class and FileInfo Class

Solution 4 - C#

Use this to obtain only the filename.

Path.GetFileName(files[0]);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNicolas RaoulView Question on Stackoverflow
Solution 1 - C#D'Arcy RittichView Answer on Stackoverflow
Solution 2 - C#Jignesh ThakkerView Answer on Stackoverflow
Solution 3 - C#Adriaan StanderView Answer on Stackoverflow
Solution 4 - C#OsirisView Answer on Stackoverflow