Directory.GetFiles: how to get only filename, not full path? [duplicate]
Asked Answered
L

4

100

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?

Leclair answered 21/9, 2012 at 4:45 Comment(0)
F
224

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.

Frater answered 21/9, 2012 at 4:48 Comment(3)
string[] files = Directory.GetFiles(dir).Select(file => Path.GetFileName(file)).ToArray();Cartie
@Justin var files = Directory.GetFiles(dir).Select(Path.GetFileName);Labradorite
Danny's comment will cause files to become an IEnumerable<string> and not a string[] just in case you needed the specific cast to a string array and access to its methods.Distance
P
41

Try,

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

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

C# Handle System.UnauthorizedAccessException in LINQ

Positivism answered 21/9, 2012 at 5:7 Comment(0)
K
9

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

Kingofarms answered 21/9, 2012 at 4:47 Comment(0)
C
4

Use this to obtain only the filename.

Path.GetFileName(files[0]);
Cornflakes answered 21/9, 2012 at 4:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.