根据文件路径将文件节点添加到树中

时间:2012-09-19 22:17:25

标签: c# algorithm tree filetree

我有结构:

public struct BaseFile
{
    public string FileName;
    public string Path; // this is not the full path. it is the fullPath of it's parent directory in other words.
}

我有班级

 public class MyFileDir // can be a file or directory
 {
      public string Name;
      public string FullPath;
      public List<MyFileDir> Children;
      public bool IsDirectory;
      // many more other properties
 }

所以我在LinkedList<BaseFile> myLinkedList上有一个线程放置文件,我希望另一个线程开始转换这些文件MyFileDir root(注意我使用了linkedList而不是list,因为linkedList的地址不会改变每次需要增长时,列表都会更改其地址

我有一个bool变量IsR​​unning,它会告诉我其他线程是否仍在向链表添加基本文件。所以我有类似的东西:

        var curNode = myLinkedList.First;

        while (IsRunning)
        {
            if (curNode.Next == null) // wait until next node is not null
            {
                Thread.Sleep(100);
                continue;
            }

            curNode = curNode.Next;
            AddItemToTree(curNode.Value);
        }

因此您可以看到我在实现方法AddItemToTree时遇到问题。我基本上希望开始在该方法中构建树。首先,我将查看根目录并搜索应添加curNode.Value的目录。我很难做到这一点。

1 个答案:

答案 0 :(得分:1)

     MyFileDir root = new MyFileDir(); //root Node

&安培;

     var curNode = myLinkedList.First;

    while (IsRunning)
    {
        if (curNode.Next == null) // wait until next node is not null
        {
            Thread.Sleep(100);
            continue;
        }

        curNode = curNode.Next;
        curFileDir = new MyFileDir(curNode);// your cast here


    List<string> mylist = curFileDir.FullPath.Split(new string[] { @"\" }, StringSplitOptions.RemoveEmptyEntries).ToList(); // this gives a list of dirs in FullPath to explore



        MyFileDir temp = root;
        foreach (string filedirName in mylist)
        {
            temp = AddNode(temp, filedirName );
        }


  }

第一个循环意味着节点是否存在返回它,否则创建它&amp;回来吧

       private MyFileDir AddNode(MyFileDir parent, string filedirName)
{
    foreach (MyFileDir subfiledir in parent.Children)
        if (subfiledir.Name == header)
            return subfiledir;

    MyFileDir filedir = new MyFileDir(fileName);
    parent.Children.Add(fileName);
    return fileName;
}