簡體   English   中英

從路徑列表填充樹視圖

[英]populate treeview from a list of path

我正在嘗試從文件夾路徑列表填充樹視圖,例如:

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'。 我已經工作了將近兩天,我的代碼中有一堆bug。 希望我能從這里得到幫助。

謝謝。

埃里克

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

替代文字

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

ehosca回答correcr,但是當我改變這樣的路徑時,有一點問題

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

            }
        }

現在它工作得很好

在此輸入圖像描述

我拿了你的代碼,它運行得很好,但是我做了一點修改,以提高加載速度,當它被用於大量的文件列表時,它似乎找到了操作,而字符串操作通常很慢

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, "\\"));

注意:可能需要在兩個解決方案中進行一些字符串靈敏度檢查,以防止某些文件夾重新創建。

\n

因為某些網址可能指向磁盤上的同一文件夾但拼寫不同,例如:Windows; WinDOWs,WINDOWS

這里有一些非常古老的代碼我曾經用來從代碼創建一個ASP.NET樹視圖(假設TreeView有一個TreeViewFolders的ID):

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

我設法只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);
}

如果所有路徑都相同,這將生成一個空樹。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM