目录中只有一个子目录时把子目录移动到父目录

直接上代码:

cs 复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProcessItems
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // 启用拖放
            treeViewItems.AllowDrop = true;

            // 拖放进入事件
            treeViewItems.DragEnter += new DragEventHandler(treeView_DragEnter);

            // 拖放事件
            treeViewItems.DragDrop += new DragEventHandler(treeView_DragDrop);
        }

        // 允许拖放的文件类型
        private void treeView_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy; // 或者其他效果
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        // 处理拖放事件
        private void treeView_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            foreach (string file in files)
            {
                // 检查文件是否存在
                if (/*File.Exists(file) || */Directory.Exists(file))
                {
                    // 在这里添加文件到TreeView的逻辑
                    treeViewItems.Nodes.Add(new TreeNode(file));
                }
            }
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            var items = GetAllTreeViewItems(treeViewItems);

            foreach (var item in items)
            {
                MoveSingleSubdirectory(item);
            }
        }

        // 递归函数,用于获取TreeView中的所有节点文本
        private static void GetTreeViewItems(TreeNodeCollection nodes, List<string> itemList)
        {
            foreach (TreeNode node in nodes)
            {
                itemList.Add(node.Text); // 添加当前节点的文本到列表中
                if (node.Nodes.Count > 0)
                {
                    // 如果当前节点有子节点,则递归调用此函数来获取子节点的文本
                    GetTreeViewItems(node.Nodes, itemList);
                }
            }
        }

        // 公共方法,供外部调用以获取TreeView中的所有项
        public static List<string> GetAllTreeViewItems(TreeView treeView)
        {
            List<string> itemList = new List<string>();
            GetTreeViewItems(treeView.Nodes, itemList);
            return itemList;
        }

        static void MoveSingleSubdirectory(string dirPath)
        {
            try
            {
                // 检查指定的目录是否存在
                if (!Directory.Exists(dirPath))
                {
                    Console.WriteLine($"目录 '{dirPath}' 不存在。");
                    return;
                }

                // 获取该目录中的所有子目录
                string[] subDirs = Directory.GetDirectories(dirPath);

                // 如果子目录数量不等于1,直接返回
                if (subDirs.Length != 1)
                {
                    Console.WriteLine($"目录 '{dirPath}' 中的子目录数量不是1。");
                    return;
                }

                // 获取唯一的子目录路径
                string subDirPath = subDirs[0];

                // 获取上一级目录路径
                string parentDirPath = Directory.GetParent(dirPath).FullName;

                // 获取当前目录的名字
                string subDirName = new DirectoryInfo(dirPath).Name;

                // 目标路径初始为上一级目录加上子目录的名字
                string destPath = Path.Combine(parentDirPath, subDirName);

                // 检查是否存在同名目录,如果存在则添加数字进行重命名
                int counter = 1;
                while (Directory.Exists(destPath))
                {
                    destPath = Path.Combine(parentDirPath, $"{subDirName}_{counter}");
                    counter++;
                }

                // 移动子目录到上一级目录
                Directory.Move(subDirPath, destPath);

                //删除空目录
                DeleteIfEmpty(parentDirPath);

                Console.WriteLine($"子目录已成功移动到: {destPath}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"操作过程中出现错误: {ex.Message}");
            }
        }

        public static bool DeleteIfEmpty(string directoryPath)
        {
            try
            {
                // 检查目录是否存在
                if (!Directory.Exists(directoryPath))
                {
                    Console.WriteLine($"目录 '{directoryPath}' 不存在。");
                    return false;
                }

                // 获取目录中的所有文件和子目录
                string[] files = Directory.GetFiles(directoryPath);
                string[] subDirs = Directory.GetDirectories(directoryPath);

                // 如果目录中没有文件也没有子目录,则认为是空目录
                if (files.Length == 0 && subDirs.Length == 0)
                {
                    // 删除空目录
                    Directory.Delete(directoryPath);
                    Console.WriteLine($"空目录 '{directoryPath}' 已被删除。");
                    return true;
                }
                else
                {
                    Console.WriteLine($"目录 '{directoryPath}' 不是空目录。");
                    return false;
                }
            }
            catch (Exception ex)
            {
                // 捕获并处理可能出现的异常
                Console.WriteLine($"操作过程中出现错误: {ex.Message}");
                return false;
            }
        }
    }
}

实现效果,可以用于整理特殊结构的目录。

相关推荐
Abigail_chow6 小时前
EXCEL如何快速批量给两字姓名中间加空格
windows·microsoft·excel·学习方法·政务
绿荫阿广8 小时前
互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(五):使用.NET为树莓派开发Wifi配网功能
c#·.net
love530love8 小时前
【笔记】在 MSYS2(MINGW64)中正确安装 Rust
运维·开发语言·人工智能·windows·笔记·python·rust
代码搬运媛10 小时前
“packageManager“: “[email protected]“ 配置如何正确启动项目?
windows·webpack
小道士写程序10 小时前
Qt 5.12 上读取 .xlsx 文件(Windows 平台)
开发语言·windows·qt
ou.cs10 小时前
c# :this() 和 :base()区别
开发语言·c#
汪小白JIY14 小时前
【C#】异步和多线程
c#·thread·async·task·threapool
宝桥南山15 小时前
DeepSeek - 尝试一下GitHub Models中的DeepSeek
microsoft·ai·微软·c#·github·.net
异常君15 小时前
Windows 与 Linux 虚拟内存机制对比:设计理念与实现差异
java·linux·windows
搏博17 小时前
将图形可视化工具的 Python 脚本打包为 Windows 应用程序
开发语言·windows·python·matplotlib·数据可视化