2013-07-15 115 views
-11

如果我不知道路徑中有多少個文件夾,並且我不知道文件夾名稱,如何從路徑中提取每個文件夾名稱?如何從路徑中提取每個文件夾的名稱?

+5

寫在第一個地方將幫助一些代碼。 – aquaraga

+0

http://stackoverflow.com/questions/3736462/c-sharp-getting-the-folder-name-from-a-path – Zaki

+0

http://stackoverflow.com/questions/2407986/get-all-sub-directories -from-a-given-path – rags

回答

5

分割字符串使用seprator:在每個子文件夾

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);   
} 
+0

+1使用DirectorySeparatorChar – rene

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"] 
+3

我會使用'System.IO.Path.DirectorySeparatorChar'而不是''\\''。 – Nolonar

2

你的意思像這樣:

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"] 
相關問題