1.在 winform 中添加2个控件buttonSearch、textBoxFileList
2. .cs文件里:
//递归实现查找目录下的所有子目录和文件
public void FindFile(string dir) //参数为指定的目录 在这里写入123
{
//在指定目录及子目录下查找文件,在listBox1中列出子目录及文件
DirectoryInfo Dir = new DirectoryInfo(dir);
try
{
foreach (DirectoryInfo d in Dir.GetDirectories()) //查找子目录
{
FindFile(Dir + d.ToString() + "\\");
textBoxFileList.Text += (Dir + d.ToString() + "\\") + "\r\n"; //添加目录名
}
foreach (FileInfo f in Dir.GetFiles("*.*")) //查找文件
{
textBoxFileList.Text += (Dir + f.ToString()) + "\r\n"; //添加文件名
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
private void buttonSearch_Click(object sender, System.EventArgs e)
{
string currentdir = "F:\\CS\\FileSearch"; //搜索的目录
if (currentdir[currentdir.Length - 1] != '\\') //非根目录
currentdir += "\\";
FindFile(currentdir); //调用查找文件函数
}
static void Delete(string path)
{
var directory = Directory.GetDirectories(path);
foreach (var t in directory)
{
if (Regex.Match(t.Trim(), @"[^\\]*$").Value == "123")
{
Directory.Delete(path + "\\123");
}
else if (Directory.GetDirectories(path).Length > 0)
Delete(t);
}
}
两三句话即可,何必那么复杂