gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:32:29 25 4
gpt4 key购买 nike

我有结构:

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 的地址不会改变,而 List 每次需要增长时都会改变其地址)

我有一个 bool 变量 IsRunning,如果另一个线程仍在将基础文件添加到链表,它会告诉我。所以我有类似的东西:

        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 的目录.我很难做到这一点。

最佳答案

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


}

第一个循环意味着如果节点存在则返回它,否则创建它并返回它

       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;
}

关于c# - 根据路径将文件节点添加到树中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12503691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com