2010-08-02 55 views
1

我正在調用這個函數來加載一個TreeView與磁盤上的目錄列表。遞歸調用正在破壞我的數據?

private void LoadDirectories(string currentPath, TreeNodeCollection nodes) 
{ 
    DirectoryInfo directoryInfo = new DirectoryInfo(currentPath); 
    DirectoryInfo[] directories = directoryInfo.GetDirectories(); 

    foreach (DirectoryInfo dir in directories) 
    { 
     if ((dir.Attributes & FileAttributes.System) != FileAttributes.System && 
      (dir.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden) 
     { 
      TreeNode newNode = nodes.Add(dir.Name); 
      LoadDirectories(dir.FullName, newNode.Nodes); 
     } 
    } 
} 

如果我註釋掉遞歸調用,我得到樹中的所有子目錄。如果我不這樣做,我不會。一些目錄丟失。我不確定發生了什麼事。

幫助?

Scott

回答

0

使用此示例代碼,它工作得很好。我建議你以此爲出發點。

static void Main(string[] args) 
{ 
    var n = LoadDirectory(@"E:\Share"); 
    Console.WriteLine(n.ToString()); 
    Console.ReadLine(); 
} 

private static Node LoadDirectory(string path) 
{ 
    var n = new Node() { Name = path }; 
    LoadDirectories(path, n); 
    return n; 
} 

private static void LoadDirectories(string currentPath, Node node) 
{ 
    DirectoryInfo directoryInfo = new DirectoryInfo(currentPath); 
    DirectoryInfo[] directories = directoryInfo.GetDirectories(); 

    foreach (DirectoryInfo dir in directories) 
    { 
     if ((dir.Attributes & FileAttributes.System) != FileAttributes.System && 
      (dir.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden) 
     { 
      var n = new Node() { Name = dir.Name }; 
      node.Children.Add(n); 
      LoadDirectories(dir.FullName, n); 
     } 
    } 
} 

private class Node 
{ 
    public List<Node> Children = new List<Node>(); 
    public string Name; 

    public override string ToString() 
    { 
     return ToString(1); 
    } 

    public string ToString(int depth) 
    { 
     if (Children.Count == 0) 
     { 
      return Name; 
     } 
     var sb = new StringBuilder(Name); 
     foreach (var n in Children) 
     { 
      sb.AppendLine(); 
      sb.Append("".PadLeft(depth, '\t') + n.ToString(depth + 1)); 
     } 
     return sb.ToString(); 
    } 
} 
0

事實證明,問題並不在於遞歸調用。問題是如果當前用戶無權訪問請求的目錄,則GetDirectories調用會拋出AccessDenied異常。

我簡單地在try/catch塊中包裝適當的調用,一切都很好。

感謝您的幫助混沌!