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?
Asked
Active
Viewed 350 times
-13
-
5Writing some code in the first place would help. – aquaraga Jul 15 '13 at 08:29
-
http://stackoverflow.com/questions/3736462/c-sharp-getting-the-folder-name-from-a-path – Zaki Jul 15 '13 at 08:29
-
http://stackoverflow.com/questions/2407986/get-all-sub-directories-from-a-given-path – rags Jul 15 '13 at 08:30
-
Do you want it to be recursivem or just in that path - As in, do you want subfolders too? – Peter Rasmussen Jul 15 '13 at 08:34
3 Answers
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