Tunc Jamgocyan
Tunc Jamgocyan

Reputation: 331

Directory name from path

with this code

string[] directories = Directory.GetDirectories(path);

I am able to get the directories in that path but I get the full path, e.g.:

C:\Users\test1\Documents\Visual Studio 2010
C:\Users\test1\Documents\test
C:\Users\test1\Documents\example

How can I get the name of the last directory!?

Upvotes: 2

Views: 411

Answers (4)

SLaks
SLaks

Reputation: 887215

Call Path.GetFileName() to get the last segment of a path.

Upvotes: 8

matt
matt

Reputation: 9401

Off the top of my head:

DirectoryInfo path = new DirectoryInfo('path to your folder');
IList<DirectoryInfo> directories = path.GetDirectories();
string last = directories.Last().Name;

The DirectoryInfo class is nice, because it gives you a little bit more information about the directory than does Directory.GetDirectories();

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

If you call

DirectoryInfo.GetDirectories(path)

you will get an array of DirectoryInfo objects, which have a Name property with the info that you are looking for.

Upvotes: 1

ie.
ie.

Reputation: 6101

Try this one:

string[] directories = Directory.GetDirectories(path).Select(x => x.Replace(path, "")).ToArray();

Do not forget to import System.Linq

Upvotes: 0

Related Questions