首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >删除目录和子目录中包含特定文本的文件

删除目录和子目录中包含特定文本的文件
EN

Stack Overflow用户
提问于 2022-10-17 14:38:59
回答 2查看 78关注 0票数 1

如何删除目录和所有子目录中包含特定字符串的文件名?

给出的文件名如下:

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“中复制不止一次,也被复制到子目录中。

我试着为这个写一个小函数。但是我可以将文件删除到给定的文件夹中,但不能删除到子文件夹中.

我的最后一个密码:

代码语言:javascript
运行
复制
// 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;
}

为了满足我的需要,我需要在这个密码中做些什么?

还是有一个完全不同的代码,更有帮助?

我希望你有一些好主意让我抓住窍门。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-10-17 14:58:05

代码语言:javascript
运行
复制
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的值,那么该文件也将被删除,我认为这是您不需要的。

票数 1
EN

Stack Overflow用户

发布于 2022-10-17 14:53:07

代码语言:javascript
运行
复制
//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); }); 

希望这能帮上忙!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74098925

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档