-13

如果我不知道路径中有多少个文件夹并且我不知道文件夹名称,如何从路径中提取每个文件夹名称?

4

3 回答 3

6

使用分隔符拆分字符串:

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

在遍历每个子文件夹并构造可能的子路径之后

var composition = string.Empty;
var directoryPathList = new List<string>();
foreach(var s in dirs) {
     composition += Path.DirectorySeparatorChar + s; 
     directoryPathList.Add(composition);         
}
于 2013-07-15T08:31:13.873 回答
5

您可以使用String.Split

string fileName = @"C:\foo\bar\baz.txt";
string directory = Path.GetDirectoryName(fileName); // "C:\foo\bar"
string allDirectoryNames = directory.Split('\\'); // ["C:", "foo", "bar"]
于 2013-07-15T08:31:16.267 回答
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"]
于 2013-07-15T08:35:21.523 回答