2008-11-25 33 views
9

我工作的東西,需要通過文件系統和任何給定的路徑遍歷,我需要知道我是如何「深」是在文件夾結構。這是我目前使用的:C#獲取給定路徑的文件夾深度的最佳方法?

int folderDepth = 0; 
    string tmpPath = startPath; 
    while (Directory.GetParent(tmpPath) != null) { 
     folderDepth++; 
     tmpPath = Directory.GetParent(tmpPath).FullName; 
    } 
    return folderDepth; 

這個工程,但我懷疑有更好/更快的方式?非常感謝任何反饋。

回答

11

關閉我的頭頂:

Directory.GetFullPath().Split("\\").Length; 
+0

就像這個想法很多!只是一個簡短的說明,長度是一種財產而不是一種方法。 – BFree 2008-11-25 00:46:09

0

如果使用Path類的成員,您可以使用路徑分隔符等路徑相關警告的本地化處理。以下代碼提供了深度(包括根)。這對糟糕的字符串等並不健壯,但這對你來說是一個開始。

 int depth = 0; 
     do 
     { 
      path = Path.GetDirectoryName(path); 
      Console.WriteLine(path); 
      ++depth; 
     } while (!string.IsNullOrEmpty(path)); 

     Console.WriteLine("Depth = " + depth.ToString()); 
2

假設你的路徑已經審覈爲是有效的,在.NET 3.5,你也可以使用LINQ做,在1行代碼......

Console.WriteLine(@」 C:\ Folder1 \ Folder2 \ Folder3 \ Folder4 \ MyFile.txt「。這裏(c => c = @」\「)。Count);

3

我總是風扇遞歸解決方案。效率低下,但很有趣!

public static int FolderDepth(string path) 
    { 
     if (string.IsNullOrEmpty(path)) 
      return 0; 
     DirectoryInfo parent = Directory.GetParent(path); 
     if (parent == null) 
      return 1; 
     return FolderDepth(parent.FullName) + 1; 
    } 

我喜歡用C#編寫的Lisp代碼!

這裏還有一個遞歸版本,我喜歡甚至更好,而且可能是更有效的:

public static int FolderDepth(string path) 
    { 
     if (string.IsNullOrEmpty(path)) 
      return 0; 
     return FolderDepth(new DirectoryInfo(path)); 
    } 

    public static int FolderDepth(DirectoryInfo directory) 
    { 
     if (directory == null) 
      return 0; 
     return FolderDepth(directory.Parent) + 1; 
    } 

美好的時光,美好的時光......

6

我比晚了更多關於這個,但我想指出保羅·索尼爾的答案可能是最短的,但應該是:

Path.GetFullPath(tmpPath).Split(Path.DirectorySeparatorChar).Length; 
相關問題