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
相关产品推荐
相关产品推荐

