You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从DevExpress XtraTreeList的TreeListNode获取文件夹路径?

解决DevExpress XtraTreeList搭配FileExplorerAssistant无法获取选中文件夹路径的问题

问题分析

你当前代码存在几个关键问题导致无法正确获取选中文件夹路径:

  • 错误通过列值获取路径:TreeList节点绑定的是PathNode对象,node.GetValue(columnname)仅能获取列显示的文件夹名称,而非完整路径。
  • 后台线程直接操作UI控件:TreeList属于UI控件,后台线程直接访问会引发线程安全异常。
  • 节点遍历效率低:遍历所有节点筛选选中项,不如直接获取选中节点集合高效。

修正后的代码

private void frmMovieAddAuto_Load(object sender, EventArgs e)
{
    // 扫描所有分区
    System.IO.DriveInfo[] driveList = System.IO.DriveInfo.GetDrives();
    foreach (var drive in driveList)
    {
        // 仅选择已就绪的固定逻辑分区
        if (drive.DriveType == System.IO.DriveType.Fixed && drive.IsReady)
        {
            // 添加每个驱动器作为根节点
            treeListExtension1.RootNodes.Add(new PathNode(drive.RootDirectory.ToString()));
        }
    }

    // 提前设置列标题,避免后台线程操作UI
    TreeListColumn columnname = treeList1.Columns[0];
    columnname.Caption = "Folder Name";
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    List<string> checkedFolderPaths = new List<string>();

    // 在主线程中获取选中节点的路径(线程安全操作)
    this.Invoke(new Action(() =>
    {
        foreach (TreeListNode node in treeList1.GetCheckedNodes())
        {
            // 直接获取节点绑定的PathNode对象,提取完整路径
            if (node.DataItem is PathNode pathNode)
            {
                checkedFolderPaths.Add(pathNode.Path); // 若PathNode的路径属性名不同,需对应修改
            }
        }
    }));

    // 后台线程处理文件扫描,不阻塞UI
    foreach (string folderPath in checkedFolderPaths)
    {
        DirectoryInfo di = new DirectoryInfo(folderPath);
        // 统一小写后缀,简化筛选条件
        foreach (FileInfo fi in di.GetFiles("*.avi;*.mpg;*.mpeg;*.mp4;*.mkv;*.divx", SearchOption.AllDirectories))
        {
            // 执行文件处理逻辑
            // 如需更新UI,可使用backgroundWorker1.ReportProgress()方法
        }
    }
}

关键修复点

  1. 正确获取完整路径:通过node.DataItem直接访问绑定的PathNode对象,提取其存储完整路径的属性(如Path),而非依赖列显示值。
  2. 线程安全处理:使用Invoke在主线程中完成TreeList节点的读取操作,后台线程仅负责文件扫描逻辑,避免跨线程UI操作异常。
  3. 优化节点获取:使用treeList1.GetCheckedNodes()直接获取所有选中节点,提升代码效率。
  4. UI操作前置:将列标题设置移至窗体加载事件,避免在后台线程重复执行UI相关操作。

内容的提问来源于stack exchange,提问作者Reza Hosseini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:45:36