public void EmptyFolder(string root, IEnumerable<string> subfolders)
{
foreach(string folder in subfolders)
{
string dirPath = Path.Combine(root, folder);
foreach (string subdir in Directory.EnumerateDirectories(dirPath))
Directory.Delete(subdir, true);
foreach (string file in Directory.EnumerateFiles(dirPath))
File.Delete(file);
}
}
// (assuming check box text is the name of folder. Or you can use tag property to set real folder name there)
private IEnumerable<string> Getfolders()
{
foreach(control c in this.Controls) // "this" being a form or control, or use specificControl.Controls
{
if (c is Checkbox check && check.Checked)
yield return check.Text;
}
}
// USAGE
EmptyFolder(@"D:\java\", Getfolders());
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
// Make an array of the checkboxes to use throughout the app.
_checkboxes = Controls.OfType<CheckBox>().ToArray();
// This provides a way to make sure the Clear button is
// only enabled when one or more checkboxes is marked.
foreach (CheckBox checkBox in _checkboxes)
{
checkBox.CheckedChanged += onAnyCheckboxChanged;
}
// Attach the 'Click' handler to the button if you
// haven't already done this in the form Designer.
buttonClear.Enabled = false;
buttonClear.Click += onClickClear;
}
const string basePath = @"D:\java\";
CheckBox[] _checkboxes;
.
.
.
}
private void onClickClear(object sender, EventArgs e)
{
// Get the checkboxes that are selected.
CheckBox[] selectedCheckBoxes =
_checkboxes.Where(_ => _.Checked).ToArray();
foreach (CheckBox checkBox in selectedCheckBoxes)
{
// Build the folder path
string folderPath = Path.Combine(basePath, checkBox.Text);
// Can't delete if it doesn't exist.
if (Directory.Exists(folderPath))
{
// Delete the directory and all its files and subfolders.
Directory.Delete(path: folderPath, recursive: true);
}
// Replace deleted folder with new, empty one.
Directory.CreateDirectory(path: folderPath);
}
}
2条答案
按热度按时间xoefb8l81#
我明白,你有这样的结构
你说 “删除文件夹的内容”。所以,我假设你需要保留文件夹
在这种情况下
注:从内存写入,未测试
0ve6wy6x2#
实现目标的众多方法之一:
1.在当前窗体上创建一个选中的复选框数组。
1.遍历数组以基于
Text
构建文件夹名称。1.删除整个文件夹,然后用一个空文件夹替换。
如果您还没有熟悉
System.Linq
扩展方法(如Where
和Any
),那么您可能需要熟悉一下。[清除]按钮应仅在选中某些内容时启用。
制作一个复选框数组会很方便。它可以在你每次
Clear
时使用。同时,除非一个或多个复选框被选中,否则不应该启用[清除]按钮。将
Clear
按钮设置为启用(或不启用)在这里,我们对复选框状态的更改做出响应。
执行清除
使用复选框的
Text
构建子文件夹路径。如果选中该复选框,则删除整个文件夹,用新的空文件夹替换它。