-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?

4
  • 5
    Writing some code in the first place would help. Commented Jul 15, 2013 at 8:29
  • stackoverflow.com/questions/3736462/… Commented Jul 15, 2013 at 8:29
  • stackoverflow.com/questions/2407986/… Commented Jul 15, 2013 at 8:30
  • Do you want it to be recursivem or just in that path - As in, do you want subfolders too? Commented Jul 15, 2013 at 8:34

3 Answers 3

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);         
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for using DirectorySeparatorChar
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"]

1 Comment

I'd use System.IO.Path.DirectorySeparatorChar instead of '\\'.
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"]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.