链接:https://ansky.lanzouo.com/iphWF2ass6ch
[C#] 纯文本查看 复制代码 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.Windows.Forms;
namespace DeleteForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnDelete_Click(object sender, EventArgs e)
{
string path = txtPath.Text.Trim();
if (Directory.Exists(path))
{
DeleteSingleItemFolders(path);
MessageBox.Show("处理完成!");
}
else
{
MessageBox.Show("指定的路径不存在!");
}
}
private void DeleteSingleItemFolders(string directory)
{
// 获取所有子文件夹
var dirs = Directory.GetDirectories(directory);
foreach (var dir in dirs)
{
// 获取子文件夹中的内容
var subDirs = Directory.GetDirectories(dir);
var files = Directory.GetFiles(dir);
// 如果只有一个子文件夹并且没有文件,则删除
if (subDirs.Length == 1 && files.Length == 0)
{
Directory.Delete(dir, true); // true 表示递归删除
MessageBox.Show($"删除文件夹: {dir}");
}
else
{
// 递归调用,检查下一级文件夹
DeleteSingleItemFolders(dir);
}
}
}
}
}
|