-13

How do I extract each folder name from a path if I don't know how many folders there are in the path and I don't know the folder names?

Rajila
  • 70
  • 3

3 Answers3

7

Split the string by using seprator:

var dirs[] = completePath.Split(Path.DirectorySeparatorChar);

after iterate over each subfolder and construct possible subpaths

var composition = string.Empty;
var directoryPathList = new List<string>();
foreach(var s in dirs) {
     composition += Path.DirectorySeparatorChar + s; 
     directoryPathList.Add(composition);         
}
Tigran
  • 61,654
  • 8
  • 86
  • 123
5

You can just use String.Split:

string fileName = @"C:\foo\bar\baz.txt";
string directory = Path.GetDirectoryName(fileName); // "C:\foo\bar"
string allDirectoryNames = directory.Split('\\'); // ["C:", "foo", "bar"]
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
2

Do you mean something like this:

String path = @"\\MyNetwork\Test\my progs\MySource.cpp";

String[] names = Path.GetDirectoryName(path).Split(new Char[] {
    Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);

// names contains ["MyNetwork", "Test", "my progs"]
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215