【问题标题】:Delete Files containing specific Text in Directory and Subdirectories删除目录和子目录中包含特定文本的文件
【发布时间】: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


【解决方案1】:
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 的值,该文件也将被删除,我认为您不希望这样。

【讨论】:

  • 非常感谢你!你的想法是对的,我不想删除包含字符串的文件夹!这几行代码非常适合我。
  • 太棒了,没问题。
【解决方案2】:
//get the list of files in the root directory and all its subdirectories:
string mypath = @"D:TEMPMYTEST";
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); }); 

希望这可以帮助!

【讨论】:

  • IIRC,IEnumerable&lt;T&gt; 上没有可用的ForEach()。开箱即用,它只存在于List&lt;T&gt; 和数组中。要修复:在调用 ToList() 之前使用 Where() 进行过滤,这也具有实现潜在更小列表的(最小)好处。
  • 感谢您的代码。在 frankM_DN 的另一个答案中,您的代码已完成,该版本对我来说工作正常。所以感谢你最初的想法和代码。
猜你喜欢
  • 1970-01-01
  • 2014-09-03
  • 2017-10-08
  • 1970-01-01
  • 2012-04-02
  • 2011-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多