如何删除目录和所有子目录中包含特定字符串的文件名?
给出的文件名如下:
EA myown EURJPY M15 3015494.mq5
EA自己的EURJPY M15 3015494.ex5
EA自EURJPY M15 3098111 fine.mq5
EA自EURJPY M15 3098111 fine.ex5
给定的Folderstructures (如:)
D:\TEMP\MYTEST
D:\TEMP\MYTEST\EURJPY
D:\TEMP\MYTEST\EURJPY\EURJPY_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;
}
为了满足我的需要,我需要在这个密码中做些什么?
还是有一个完全不同的代码,更有帮助?
我希望你有一些好主意让我抓住窍门。
发布于 2022-10-17 14:58:05
DirectoryInfo dir = new DirectoryInfo(mypath);
// get all the files in the directory.
// SearchOptions.AllDirectories gets all the files in subdirectories as well
FileInfo[] files = dir.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo file in files)
{
if (file.Name.Contains(myfilecontains))
{
File.Delete(file.FullName);
}
}这类似于hossein的回答,但在他的答案中,如果目录名包含myfilecontains的值,那么该文件也将被删除,我认为这是您不需要的。
发布于 2022-10-17 14:53:07
//get the list of files in the root directory and all its subdirectories:
string mypath = @"D:\TEMP\MYTEST\";
string myfilecontains = @"xx";
var files = Directory.GetFiles(mypath, "*", SearchOption.AllDirectories).ToList<string>();
//get the list of file for remove
var forDelete = files.Where(x => x.Contains(myfilecontains));
//remove files
forDelete.ForEach(x => { File.Delete(x); }); 希望这能帮上忙!
https://stackoverflow.com/questions/74098925
复制相似问题