0

I have following code that reads folder names given a path.

string[] dirNames =(Directory.GetDirectories(@"c:\test\project\"));
foreach(string name in dirNames)
{
   Console.WriteLine(name);
}

Problem is that dirNames array is storing the directory name with path. While I just want to store the directory file name no path. I can remove it in the foreach loop but I want to store originally in the array with out path. Please let me know how to fix it. Thanks

Omar
  • 16,329
  • 10
  • 48
  • 66
J. Davidson
  • 3,297
  • 13
  • 54
  • 102

4 Answers4

0

Use GetDirectoryName from the Path class:

  foreach(string name in dirNames)
  {
      Console.WriteLine(Path.GetDirectoryName( name ));
  }
quantdev
  • 23,517
  • 5
  • 55
  • 88
0

What about:

string[] dirNames = Directory.GetDirectories(@"c:\test\project\").Select(x => Path.GetDirectoryName(x)).ToArray();
Omar
  • 16,329
  • 10
  • 48
  • 66
0

You can get a new array (or list) in which the path is removed:

var dirNamesNew = dirNames.Select( x => x.Replace(path,"")).ToArray();

or in a single instruction:

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

the Select will fetch the names, replace the path with no character, and then convert it back to an Array.

Saverio Terracciano
  • 3,885
  • 1
  • 30
  • 42
0

Try creating a DirectoryInfo and projecting the name for each directory:

var onlyDirectoryNames = Directory.GetDirectories(@"c:\test\project\").Select(x => new DirectoryInfo(x).Name)
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321