Fuzz Evans
Fuzz Evans

Reputation: 2943

How can I return a directories files/folders without the directory path included?

I am trying to extract a list of files within a folder and am currently using:

 string[] files = Directory.GetFiles(txtbxNewFolder.Text);

But that returns things like "C:\Users\Dahlia\Desktop\New Folder\jerry.txt". Is there a way to return only "jerry.txt", or do I need to do some sort of split on the array strings?

I am also trying to return a list of folders within a directory and am currently using:

string[] folders = Directory.GetDirectories(txtbxOldFolder.Text);

But that returns things like "C:\Users\Dahlia\Desktop\New Folder\folder1". Is there a way to return only "folder1", or do I need to do some sort of split on the array strings?

Upvotes: 3

Views: 5751

Answers (3)

M.Babcock
M.Babcock

Reputation: 18965

Using LINQ you can get a list of just the files:

Directory.GetFiles(txtbxNewFolder.Text).Select(f => Path.GetFileName(f));

Though rather than GetFiles I'd probably use:

Directory.EnumerateFiles(txtbxNewFolder.Text).Select(f => Path.GetFileName(f));

It isn't as simple to get the directory name, but this should work (untested):

Directory.GetDirectories(txtbxOldFolder.Text)
    .Select(d => new DirectoryInfo(d).Name);

Similarly, there is a:

Directory.EnumerateDirectories(txtbxOldFolder.Text)
    .Select(d => new DirectoryInfo(d).Name);

Upvotes: 15

Chris Shain
Chris Shain

Reputation: 51359

Have a look at the FileInfo and DirectoryInfo classes.

You can do:

foreach (String file in files) {
    var fi = new FileInfo(file);
    Console.Out.WriteLine(fi.Name);
}

Similar for DirectoryInfo.

Upvotes: 1

Terkel
Terkel

Reputation: 1575

You could use Path.GetFileName and LINQ

e.g.:

string[] files = Directory.GetFiles(txtbxNewFolder.Text)
                          .Select(f => Path.GetFileName(s))
                          .ToArray();

Upvotes: 4

Related Questions