从路径列表填充树视图

发布于 2024-07-27 13:57:02 字数 650 浏览 5 评论 0原文

我正在尝试从文件夹路径列表填充树视图,例如:

C:\WINDOWS\addins
C:\WINDOWS\AppPatch
C:\WINDOWS\AppPatch\MUI
C:\WINDOWS\AppPatch\MUI\040C
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI\0409

使用如下输出:

├───addins
├───AppPatch
│   └───MUI
│       └───040C
├───Microsoft.NET
│   └───Framework
│       └───v2.0.50727
│           └───MUI
│               └───0409

注意,没有 'C:\WINDOWS\Microsoft.NET' 或 'C:\WINDOWS\Microsoft.NET\Framework'在列表中。 我已经为此工作了近两天,我的代码中有很多错误。 希望我能从这里得到帮助。

谢谢。

埃里克

I'm trying to populate a treeview from a list of folder path, for example:

C:\WINDOWS\addins
C:\WINDOWS\AppPatch
C:\WINDOWS\AppPatch\MUI
C:\WINDOWS\AppPatch\MUI\040C
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI\0409

with an ouput like this:

├───addins
├───AppPatch
│   └───MUI
│       └───040C
├───Microsoft.NET
│   └───Framework
│       └───v2.0.50727
│           └───MUI
│               └───0409

Notice there's no 'C:\WINDOWS\Microsoft.NET' or 'C:\WINDOWS\Microsoft.NET\Framework' in the list. I've been working on this for almost two days and there's a bunch of bug in my code. Hope I can get help from here.

Thanks.

Eric

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

江湖正好 2024-08-03 13:57:02
private void Form1_Load(object sender, EventArgs e)
    {
        var paths = new List<string>
                        {
                            @"C:\WINDOWS\AppPatch\MUI\040C",
                            @"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727",
                            @"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI",
                            @"C:\WINDOWS\addins",
                            @"C:\WINDOWS\AppPatch",
                            @"C:\WINDOWS\AppPatch\MUI",
                            @"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI\0409"
                        };

        treeView1.PathSeparator = @"\";

        PopulateTreeView(treeView1, paths, '\\');
}


private static void PopulateTreeView(TreeView treeView, IEnumerable<string> paths, char pathSeparator)
    {
        TreeNode lastNode = null;
        string subPathAgg;
        foreach (string path in paths)
        {
            subPathAgg = string.Empty;
            foreach (string subPath in path.Split(pathSeparator))
            {
                subPathAgg += subPath + pathSeparator;
                TreeNode[] nodes = treeView.Nodes.Find(subPathAgg, true);
                if (nodes.Length == 0)
                    if (lastNode == null)
                        lastNode = treeView.Nodes.Add(subPathAgg, subPath);
                    else
                        lastNode = lastNode.Nodes.Add(subPathAgg, subPath);
                else
                    lastNode = nodes[0];
            }
        }
    }

替代文字

private void Form1_Load(object sender, EventArgs e)
    {
        var paths = new List<string>
                        {
                            @"C:\WINDOWS\AppPatch\MUI\040C",
                            @"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727",
                            @"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI",
                            @"C:\WINDOWS\addins",
                            @"C:\WINDOWS\AppPatch",
                            @"C:\WINDOWS\AppPatch\MUI",
                            @"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI\0409"
                        };

        treeView1.PathSeparator = @"\";

        PopulateTreeView(treeView1, paths, '\\');
}


private static void PopulateTreeView(TreeView treeView, IEnumerable<string> paths, char pathSeparator)
    {
        TreeNode lastNode = null;
        string subPathAgg;
        foreach (string path in paths)
        {
            subPathAgg = string.Empty;
            foreach (string subPath in path.Split(pathSeparator))
            {
                subPathAgg += subPath + pathSeparator;
                TreeNode[] nodes = treeView.Nodes.Find(subPathAgg, true);
                if (nodes.Length == 0)
                    if (lastNode == null)
                        lastNode = treeView.Nodes.Add(subPathAgg, subPath);
                    else
                        lastNode = lastNode.Nodes.Add(subPathAgg, subPath);
                else
                    lastNode = nodes[0];
            }
        }
    }

alt text

萌面超妹 2024-08-03 13:57:02

ehosca 答案是正确的,但有一个小问题,
当我将路径更改为这样的

C:\WINDOWS\AppPatch\MUI\040C
D:\WIS\Microsoft.NET\Framework\v2.0.50727
E:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI
C:\WINDOWS\addins
C:\WINDOWS\AppPatch
C:\WINDOWS\AppPatch\MUI
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI\0409

在此处输入图像描述

它将像这样填充树视图。

但是添加一些额外的代码我们可以避免这种情况。 所以我更改了 PopulateTreeView 中的代码

private static void PopulateTreeView(TreeView treeView, string[] paths, char pathSeparator)
        {
            TreeNode lastNode = null;
            string subPathAgg;
            foreach (string path in paths)
            {
                subPathAgg = string.Empty;
                foreach (string subPath in path.Split(pathSeparator))
                {
                    subPathAgg += subPath + pathSeparator;
                    TreeNode[] nodes = treeView.Nodes.Find(subPathAgg, true);
                    if (nodes.Length == 0)
                        if (lastNode == null)
                            lastNode = treeView.Nodes.Add(subPathAgg, subPath);
                        else
                            lastNode = lastNode.Nodes.Add(subPathAgg, subPath);
                    else
                        lastNode = nodes[0];
                }
                lastNode = null; // This is the place code was changed

            }
        }

现在它工作正常,如下所示

在此处输入图像描述

ehosca answer is correcr, but there is a little problem,
when I change paths to like this

C:\WINDOWS\AppPatch\MUI\040C
D:\WIS\Microsoft.NET\Framework\v2.0.50727
E:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI
C:\WINDOWS\addins
C:\WINDOWS\AppPatch
C:\WINDOWS\AppPatch\MUI
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI\0409

enter image description here

It will popoulate treeview like this.

But adding some extra code we can avoid this situation. So I changed the code in PopulateTreeView

private static void PopulateTreeView(TreeView treeView, string[] paths, char pathSeparator)
        {
            TreeNode lastNode = null;
            string subPathAgg;
            foreach (string path in paths)
            {
                subPathAgg = string.Empty;
                foreach (string subPath in path.Split(pathSeparator))
                {
                    subPathAgg += subPath + pathSeparator;
                    TreeNode[] nodes = treeView.Nodes.Find(subPathAgg, true);
                    if (nodes.Length == 0)
                        if (lastNode == null)
                            lastNode = treeView.Nodes.Add(subPathAgg, subPath);
                        else
                            lastNode = lastNode.Nodes.Add(subPathAgg, subPath);
                    else
                        lastNode = nodes[0];
                }
                lastNode = null; // This is the place code was changed

            }
        }

Now it works fine like this

enter image description here

慈悲佛祖 2024-08-03 13:57:02

对于 linq'y 版本:

public static TreeNode MakeTreeFromPaths(List<string> paths, string rootNodeName = "", char separator = '/')
{
    var rootNode = new TreeNode(rootNodeName);
    foreach (var path in paths.Where(x => !string.IsNullOrEmpty(x.Trim()))) {
        var currentNode = rootNode;
        var pathItems = path.Split(separator);
        foreach (var item in pathItems) {
            var tmp = currentNode.Nodes.Cast<TreeNode>().Where(x => x.Text.Equals(item));
            currentNode = tmp.Count() > 0 ? tmp.Single() : currentNode.Nodes.Add(item);
        }
    }
    return rootNode;
}

for a linq'y version:

public static TreeNode MakeTreeFromPaths(List<string> paths, string rootNodeName = "", char separator = '/')
{
    var rootNode = new TreeNode(rootNodeName);
    foreach (var path in paths.Where(x => !string.IsNullOrEmpty(x.Trim()))) {
        var currentNode = rootNode;
        var pathItems = path.Split(separator);
        foreach (var item in pathItems) {
            var tmp = currentNode.Nodes.Cast<TreeNode>().Where(x => x.Text.Equals(item));
            currentNode = tmp.Count() > 0 ? tmp.Single() : currentNode.Nodes.Add(item);
        }
    }
    return rootNode;
}
哆啦不做梦 2024-08-03 13:57:02

我拿了你的代码,它运行得很好,
但我只是做了一点修改来提高加载速度
当它用于大量文件列表时
看起来像查找操作,而字符串操作通常非常慢,

private TreeNode PopulateTreeNode2(string[] paths, string pathSeparator)
    {
        if (paths == null)
            return null;

        TreeNode thisnode = new TreeNode();
        TreeNode currentnode;
        char[] cachedpathseparator = pathSeparator.ToCharArray();
        foreach (string path in paths)            {
            currentnode = thisnode;
            foreach (string subPath in path.Split(cachedpathseparator))
            {
                if (null == currentnode.Nodes[subPath])
                    currentnode = currentnode.Nodes.Add(subPath, subPath);
                else
                    currentnode = currentnode.Nodes[subPath];                   
            }
        }

        return thisnode;
    }

那么您可以使用:

string[] paths =  {
                        @"C:\WINDOWS\AppPatch\MUI\040C",
                        @"D:\WINDOWS\Microsoft.NET\Framework\v2.0.50727",
                        @"E:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI",
                        @"C:\WINDOWS\addins",
                        @"C:\WINDOWS\AppPatch",
                        @"C:\WINDOWS\AppPatch\MUI",
                        @"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI\0409"
                    };
TreeView treeview = new TreeView();
treeview.Nodes.Add(PopulateTreeNode2(paths, "\\"));

注意:两种解决方案中可能都需要一些字符串敏感性检查,
为了防止重新创建某些文件夹。

因为某些 url 可能指向磁盘上的同一文件夹
但拼写不同,例如:
窗户; Windows , WINDOWS

I took your code, and it work very well,
but i made just a little modification for improving the load speed
when it is used whit a large list of files
it seems like find operation, and string operations generally are very slow

private TreeNode PopulateTreeNode2(string[] paths, string pathSeparator)
    {
        if (paths == null)
            return null;

        TreeNode thisnode = new TreeNode();
        TreeNode currentnode;
        char[] cachedpathseparator = pathSeparator.ToCharArray();
        foreach (string path in paths)            {
            currentnode = thisnode;
            foreach (string subPath in path.Split(cachedpathseparator))
            {
                if (null == currentnode.Nodes[subPath])
                    currentnode = currentnode.Nodes.Add(subPath, subPath);
                else
                    currentnode = currentnode.Nodes[subPath];                   
            }
        }

        return thisnode;
    }

then you can use:

string[] paths =  {
                        @"C:\WINDOWS\AppPatch\MUI\040C",
                        @"D:\WINDOWS\Microsoft.NET\Framework\v2.0.50727",
                        @"E:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI",
                        @"C:\WINDOWS\addins",
                        @"C:\WINDOWS\AppPatch",
                        @"C:\WINDOWS\AppPatch\MUI",
                        @"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI\0409"
                    };
TreeView treeview = new TreeView();
treeview.Nodes.Add(PopulateTreeNode2(paths, "\\"));

NOTE: maybe some string sensitivity check will be needed in both solutions,
in order to prevent some folders re creations.

because some url could be pointing to the same folder on the disk
but spelled different such as:
Windows ; WinDOWs , WINDOWS

2024-08-03 13:57:02

我尝试了 ykm29 的代码,但它无法正确填充子文件夹。 这里的一些其他答案也使用单个路径部分来识别创建的 TreeNodes。 如果不同目录中存在重复的文件夹名称,可能会导致我认为的问题。

因此,在我的代码中,我将“currentPath”值设置为我为文件夹获取的 TreeNodes 的键。 下面代码中的“ExtendedFileInfo”扩展了“FileInfo”类,并为我自己的用例添加了一些附加属性。 在调用此函数之前,创建根节点并将其分配给 TreeView。

private void MakeTreeViewFromPaths(TreeNode rootNode, List<ExtendedFileInfo> files, string rootNodeName = "C:\\", char separator = '\\')
    {
        foreach (var file in files)
        {
            TreeNode currentNode = rootNode;
            string[] relPath = file.RelativePath.Split(separator);
            string currentPath = rootNodeName;  

            //**Split operation always generates an empty entry so we use "-1" to avoid iterating through the last empty array item
            for (int i = 0; i < relPath.Length - 1; i++)
            {
                currentPath += "\\" + relPath[i];
                TreeNode[] tmp = currentNode.Nodes.Find(currentPath, false);
                if (tmp.Length > 0)
                {
                    currentNode = tmp[0];
                    continue;
                }
                //Create Folder Nodes
                currentNode = currentNode.Nodes.Add(currentPath, relPath[i]);
            }

            //Create File Nodes
            TreeNode newNode = new TreeNode(file.FileInfo.Name);
            newNode.Tag = file;
            currentNode.Nodes.Add(newNode);
        }
    }

I tried ykm29's code but it couldn't properly populate the subfolders. Some other answers here were also using a single path part to identify created TreeNodes. In case there are duplicate folder names in different directories it might cause issues I thought.

So in my code I set "currentPath" value as the Key for TreeNodes i got for folders. "ExtendedFileInfo" in below code extends "FileInfo" class with few additional properties for my own usecase. Before you call this function create your root node and assign it to your TreeView.

private void MakeTreeViewFromPaths(TreeNode rootNode, List<ExtendedFileInfo> files, string rootNodeName = "C:\\", char separator = '\\')
    {
        foreach (var file in files)
        {
            TreeNode currentNode = rootNode;
            string[] relPath = file.RelativePath.Split(separator);
            string currentPath = rootNodeName;  

            //**Split operation always generates an empty entry so we use "-1" to avoid iterating through the last empty array item
            for (int i = 0; i < relPath.Length - 1; i++)
            {
                currentPath += "\\" + relPath[i];
                TreeNode[] tmp = currentNode.Nodes.Find(currentPath, false);
                if (tmp.Length > 0)
                {
                    currentNode = tmp[0];
                    continue;
                }
                //Create Folder Nodes
                currentNode = currentNode.Nodes.Add(currentPath, relPath[i]);
            }

            //Create File Nodes
            TreeNode newNode = new TreeNode(file.FileInfo.Name);
            newNode.Tag = file;
            currentNode.Nodes.Add(newNode);
        }
    }
我的黑色迷你裙 2024-08-03 13:57:02

下面是我曾经用来从代码创建 ASP.NET 树视图的一些非常旧的代码(假设 TreeView 的 ID 为 TreeViewFolders):

protected void Page_Load(object sender, EventArgs e)
{
    GenerateTreeView(@"C:\WINDOWS\");
}

private void GenerateTreeView(string rootPath)
{
    GetFolders(System.IO.Path.GetFullPath(rootPath), TreeViewFolders.Nodes);
    TreeViewFolders.ExpandDepth = 1;
}

// recursive method to load all folders and files into tree
private void GetFolders(string path, TreeNodeCollection nodes)
{
    // add nodes for all directories (folders)
    string[] dirs = Directory.GetDirectories(path);
    foreach (string p in dirs)
    {
        string dp = p.Substring(path.Length);
        nodes.Add(Node("", p.Substring(path.Length), "folder"));
    }

    // add nodes for all files in this directory (folder)
    string[] files = Directory.GetFiles(path, "*.*");
    foreach (string p in files)
    {
        nodes.Add(Node(p, p.Substring(path.Length), "file"));
    }

    // add all subdirectories for each directory (recursive)
    for (int i = 0; i < nodes.Count; i++)
    {
        if (nodes[i].Value == "folder")
            GetFolders(dirs[i] + "\\", nodes[i].ChildNodes);
    }
}

// create a TreeNode from the specified path, text and type
private TreeNode Node(string path, string text, string type)
{
    TreeNode n = new TreeNode();
    n.Value = type;
    n.Text = text;
    return n;
}

Here's some very old code I once used to create an ASP.NET treeview from code (assuming TreeView has an ID of TreeViewFolders):

protected void Page_Load(object sender, EventArgs e)
{
    GenerateTreeView(@"C:\WINDOWS\");
}

private void GenerateTreeView(string rootPath)
{
    GetFolders(System.IO.Path.GetFullPath(rootPath), TreeViewFolders.Nodes);
    TreeViewFolders.ExpandDepth = 1;
}

// recursive method to load all folders and files into tree
private void GetFolders(string path, TreeNodeCollection nodes)
{
    // add nodes for all directories (folders)
    string[] dirs = Directory.GetDirectories(path);
    foreach (string p in dirs)
    {
        string dp = p.Substring(path.Length);
        nodes.Add(Node("", p.Substring(path.Length), "folder"));
    }

    // add nodes for all files in this directory (folder)
    string[] files = Directory.GetFiles(path, "*.*");
    foreach (string p in files)
    {
        nodes.Add(Node(p, p.Substring(path.Length), "file"));
    }

    // add all subdirectories for each directory (recursive)
    for (int i = 0; i < nodes.Count; i++)
    {
        if (nodes[i].Value == "folder")
            GetFolders(dirs[i] + "\\", nodes[i].ChildNodes);
    }
}

// create a TreeNode from the specified path, text and type
private TreeNode Node(string path, string text, string type)
{
    TreeNode n = new TreeNode();
    n.Value = type;
    n.Text = text;
    return n;
}
攒一口袋星星 2024-08-03 13:57:02
private void Form2_Load(object sender, EventArgs e)
{
    treeView1.CheckBoxes = true;

    foreach (TreeNode node in treeView1.Nodes)
    {
        node.Checked = true;
    }

    string[] drives = Environment.GetLogicalDrives();

    foreach (string drive in drives)
    {
        // treeView1.Nodes[0].Nodes[1].Checked = true;
        DriveInfo di = new DriveInfo(drive);
        int driveImage;

        switch (di.DriveType)   
        {
            case DriveType.CDRom:
                driveImage = 3;
                break;
            case DriveType.Network:
                driveImage = 6;
                break;
            case DriveType.NoRootDirectory:
                driveImage = 8;
                break;
            case DriveType.Unknown:
                driveImage = 8;
                break;
            default:
                driveImage = 2;
                break;
        }

        TreeNode node = new TreeNode(drive.Substring(0, 1), driveImage, driveImage);
        node.Tag = drive;

        if (di.IsReady == true)
             node.Nodes.Add("...");

        treeView1.Nodes.Add(node);          
    }

    foreach (TreeNode node in treeView1.Nodes)
    {
        node.Checked = true;
    }
}

private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
    {
        if (e.Node.Nodes.Count > 0)
        {
            if (e.Node.Nodes[0].Text == "..." && e.Node.Nodes[0].Tag == null)
            {
                e.Node.Nodes.Clear();

                string[] dirs = Directory.GetDirectories(e.Node.Tag.ToString());

                foreach (string dir in dirs)
                {
                    DirectoryInfo di = new DirectoryInfo(dir);
                    TreeNode node = new TreeNode(di.Name, 0, 1);
                    node.Checked = true;

                    try
                    {
                        node.Tag = dir;
                        if (di.GetDirectories().Count() > 0)
                            node.Nodes.Add(null, "...", 0, 0).Checked = node.Checked;
                    }
                    catch (UnauthorizedAccessException)
                    {
                        node.ImageIndex = 12;
                        node.SelectedImageIndex = 12;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "DirectoryLister", MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    }
                    finally
                    {
                        node.Checked = e.Node.Checked;
                        e.Node.Nodes.Add(node);
                    }
                }
            }
        }
    }              
}

private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
    button1.Enabled = false;
    TreeNode node = e.Node;
    bool is_checked = node.Checked;
    foreach (TreeNode childNode in e.Node.Nodes)
    {
        childNode.Checked = e.Node.Checked;
    }
    treeView1.SelectedNode = node;
 }
private void Form2_Load(object sender, EventArgs e)
{
    treeView1.CheckBoxes = true;

    foreach (TreeNode node in treeView1.Nodes)
    {
        node.Checked = true;
    }

    string[] drives = Environment.GetLogicalDrives();

    foreach (string drive in drives)
    {
        // treeView1.Nodes[0].Nodes[1].Checked = true;
        DriveInfo di = new DriveInfo(drive);
        int driveImage;

        switch (di.DriveType)   
        {
            case DriveType.CDRom:
                driveImage = 3;
                break;
            case DriveType.Network:
                driveImage = 6;
                break;
            case DriveType.NoRootDirectory:
                driveImage = 8;
                break;
            case DriveType.Unknown:
                driveImage = 8;
                break;
            default:
                driveImage = 2;
                break;
        }

        TreeNode node = new TreeNode(drive.Substring(0, 1), driveImage, driveImage);
        node.Tag = drive;

        if (di.IsReady == true)
             node.Nodes.Add("...");

        treeView1.Nodes.Add(node);          
    }

    foreach (TreeNode node in treeView1.Nodes)
    {
        node.Checked = true;
    }
}

private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
    {
        if (e.Node.Nodes.Count > 0)
        {
            if (e.Node.Nodes[0].Text == "..." && e.Node.Nodes[0].Tag == null)
            {
                e.Node.Nodes.Clear();

                string[] dirs = Directory.GetDirectories(e.Node.Tag.ToString());

                foreach (string dir in dirs)
                {
                    DirectoryInfo di = new DirectoryInfo(dir);
                    TreeNode node = new TreeNode(di.Name, 0, 1);
                    node.Checked = true;

                    try
                    {
                        node.Tag = dir;
                        if (di.GetDirectories().Count() > 0)
                            node.Nodes.Add(null, "...", 0, 0).Checked = node.Checked;
                    }
                    catch (UnauthorizedAccessException)
                    {
                        node.ImageIndex = 12;
                        node.SelectedImageIndex = 12;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "DirectoryLister", MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    }
                    finally
                    {
                        node.Checked = e.Node.Checked;
                        e.Node.Nodes.Add(node);
                    }
                }
            }
        }
    }              
}

private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
    button1.Enabled = false;
    TreeNode node = e.Node;
    bool is_checked = node.Checked;
    foreach (TreeNode childNode in e.Node.Nodes)
    {
        childNode.Checked = e.Node.Checked;
    }
    treeView1.SelectedNode = node;
 }
笑,眼淚并存 2024-08-03 13:57:02

我已经成功地仅使用 for 循环从路径列表创建了一棵树。 而现在看来,这就是这个问题最简单的答案了。

使用此代码块创建一棵树。 list 是文件或文件夹的列表,treeView1 是您的 TreeView。

//Creates a tree from given path list
foreach (string path in list)
{
    TreeNodeCollection nodes = treeView1.Nodes;

    foreach (string path_part in path.Split('\\'))
    {
        //Here it adds a new node (file or folder)
        if (!nodes.ContainsKey(path_part))
            nodes.Add(path_part, path_part);
        //Go one node deeper
        nodes = nodes[path_part].Nodes;
    }
}

注意 - 如果您将其与以路径分隔符开头的路径一起使用(例如 /home/user),

并且如果您想删除路径的公共部分(或删除单个父节点),则 这可能会中断,在上一个代码块之后使用此代码块:

//This removes "single" TreeNodes (common paths)
while (treeView1.Nodes.Count == 1)
{
    //This "unpacks" child TreeNodes from the only parent TreeNode
    for (int i = 0; i < treeView1.Nodes[0].Nodes.Count; i++)
        treeView1.Nodes.Add(treeView1.Nodes[0].Nodes[i]);
    //This removes parent TreeNode
    treeView1.Nodes.RemoveAt(0);
}

如果所有路径都相同,这将生成一棵空树。

I've managed to create a tree from path list using only for cycles. And it looks like it is the simpliest answer of this question at this moment.

Use this block of code to create a tree. list is the list of your files or folders, treeView1 is your TreeView.

//Creates a tree from given path list
foreach (string path in list)
{
    TreeNodeCollection nodes = treeView1.Nodes;

    foreach (string path_part in path.Split('\\'))
    {
        //Here it adds a new node (file or folder)
        if (!nodes.ContainsKey(path_part))
            nodes.Add(path_part, path_part);
        //Go one node deeper
        nodes = nodes[path_part].Nodes;
    }
}

Note - this may break if you use it with paths that start with the path separator (e.g. /home/user)

And if you want to remove common parts of your paths (or remove single parent nodes), use this block of code right after the previous one:

//This removes "single" TreeNodes (common paths)
while (treeView1.Nodes.Count == 1)
{
    //This "unpacks" child TreeNodes from the only parent TreeNode
    for (int i = 0; i < treeView1.Nodes[0].Nodes.Count; i++)
        treeView1.Nodes.Add(treeView1.Nodes[0].Nodes[i]);
    //This removes parent TreeNode
    treeView1.Nodes.RemoveAt(0);
}

This will generate an empty tree if all of your paths are the same.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文