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

WinForm双TreeView分属不同磁盘路径实现问题求助

解决方案

核心思路

复用同一个下拉框加载Z盘的子文件夹(因R、Z盘结构完全一致),生成文件夹时:

  • loremPath 直接使用下拉框选中的Z盘路径作为基础路径
  • ipsumPath 将下拉框选中的Z盘路径替换为R盘路径,保持相对目录结构一致

具体代码修改

1. 修正下拉框初始化(Form构造函数)

移除多余的ipsumDropDown,复用loremDropDown加载Z盘目录:

public Form1()
{
    InitializeComponent();
    this.FormBorderStyle = FormBorderStyle.None;
    Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 20, 20));
    foreach (TreeNode tn in loremPath.Nodes)
    {
        tn.Expand();
    }
    foreach (TreeNode tn in ipsumPath.Nodes)
    {
        tn.Expand();
    }
    
    // 加载Z盘的子文件夹到下拉框,显示名称,值为完整路径
    var zDirs = new DirectoryInfo(@"Z:\").GetDirectories();
    loremDropDown.DataSource = zDirs;
    loremDropDown.DisplayMember = "Name";
    loremDropDown.ValueMember = "FullName";
}

2. 修改文件夹生成逻辑(projektordnerGenerieren_Click方法)

区分两个TreeView对应的目标盘路径,替换路径前缀实现R盘映射:

private void projektordnerGenerieren_Click(object sender, EventArgs e)
{
    // 获取下拉框选中的Z盘目标路径
    string zTargetPath = loremDropDown.SelectedValue.ToString();
    // 替换路径前缀,得到R盘的对应目标路径
    string rTargetPath = zTargetPath.Replace(@"Z:\", @"R:\");

    var dirSep = Path.DirectorySeparatorChar.ToString();
    var treeSep = loremPath.PathSeparator.ToString();

    // 处理loremPath(Z盘)
    foreach (var node in GetCheckedNodes(loremPath.Nodes))
    {
        var relativePath = node.FullPath.Replace(treeSep, dirSep);
        var fullPath = Path.Combine(zTargetPath, relativePath);
        Directory.CreateDirectory(fullPath);
    }

    // 处理ipsumPath(R盘)
    foreach (var node in GetCheckedNodes(ipsumPath.Nodes))
    {
        var relativePath = node.FullPath.Replace(treeSep, dirSep);
        var fullPath = Path.Combine(rTargetPath, relativePath);
        Directory.CreateDirectory(fullPath);
    }

    string folder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    CreateShortcutToCurrentAssembly(folder);
}

关键修正点

  • 移除了之前错误的testPath.ToString()操作(该操作会返回类型名称而非路径)
  • 通过路径前缀替换实现R/Z盘的目录映射,无需额外下拉框
  • 确保两个TreeView的选中节点分别生成到对应盘的同结构目录下

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:05:48