【发布时间】:2023-01-04 02:08:53
【问题描述】:
如何删除名称中包含目录和所有子目录中特定字符串的文件?
给定文件名,例如:
EA myown EURJPY M15 3015494.mq5
EA myown EURJPY M15 3015494.ex5
EA 自 EURJPY M15 3098111 fine.mq5
EA 自 EURJPY M15 3098111 fine.ex5
给定的文件夹结构如下:
D:\TEMP\我的测试
D:\TEMP\MYTEST\EURJPY
D:\TEMP\MYTEST\EUR 日元\EUR 日元 M15
示例:我想删除包含此字符串的所有子目录中的所有文件:
3015494
这些文件被多次复制到根文件夹“D:\TEMP\MYTEST”下,并复制到子目录中。
我尝试为此编写一个小函数。但是我可以将文件删除到给定的文件夹中,但不能删除到子文件夹中......
我的最后代码:
// call my function to delete files ...
string mypath = @"D:\TEMP\MYTEST\";
string myfilecontains = @"xx";
DeleteFile(mypath, true, myfilecontains);
// some code i found here and should delete just Files,
// but only works in Root-Dir.
// Also will not respect my need for Filename contains Text
public static bool DeleteFile(string folderPath, bool recursive, string FilenameContains)
{
//Safety check for directory existence.
if (!Directory.Exists(folderPath))
return false;
foreach (string file in Directory.GetFiles(folderPath))
{
File.Delete(file);
}
//Iterate to sub directory only if required.
if (recursive)
{
foreach (string dir in Directory.GetDirectories(folderPath))
{
//DeleteFile(dir, recursive);
MessageBox.Show(dir);
}
}
//Delete the parent directory before leaving
//Directory.Delete(folderPath);
return true;
}
我必须根据自己的需要更改此代码中的哪些内容?
或者是否有一个完全不同的代码更有帮助?
我希望你有一些好主意让我抓住这个把戏。
【问题讨论】:
-
好吧,至少现在你对
DeleteFile的递归调用被注释掉了,所以它不会运行。
标签: c# .net .net-core delete-file