从目录中删除的文件,如果文件名包含某个词 [英] Delete files from directory if filename contains a certain word

查看:415
本文介绍了从目录中删除的文件,如果文件名包含某个词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一个目录,看看是否有任何文件,其文件名中包含特定关键字,如果有,将其删除。 ?这是可能的。

I need to check a directory to see if there are any files whose file name contains a specific keyword and if there are, to delete them. Is this possible?

例如,删除所有现有文件 C:\Folder 的文件名。包含关键字苹果

For example, delete all existing files in "C:\Folder" whose file name contains the keyword "Apple".

推荐答案

要扩大亨克的答案,你需要:

To expand on Henk's answer, you need:

string rootFolderPath = @"C:\\SomeFolder\\AnotherFolder\\FolderCOntainingThingsToDelete";
string filesToDelete = @"*DeleteMe*.doc";   // Only delete DOC files containing "DeleteMe" in their filenames
string[] fileList = System.IO.Directory.GetFiles(rootFolderPath, filesToDelete);
foreach(string file in fileList)
{
    System.Diagnostics.Debug.WriteLine(file + "will be deleted");
//  System.IO.File.Delete(file);
}



要非常小心!

请注意,我已经注释掉delete命令。运行并测试它的仔细的你让它真正删除任何东西之前!

Note that I've commented out the delete command. Run it and test it carefully before you let it actually delete anything!

如果你想在根文件夹的所有子文件夹递归地删除文件,添加System.IO.SearchOption.AllDirectories);到的GetFiles调用。

If you wish to recursively delete files in ALL subfolders of the root folder, add ,System.IO.SearchOption.AllDirectories); to the GetFiles call.

如果你做到这一点也是一个非常好主意,拒绝运行,如果rootFolderPath小于约4字符(一个简单的防止删除用C一切:\ - 我去过那里,这样做,它是不好玩!)

If you do this it is also a very good idea to refuse to run if the rootFolderPath is less than about 4 characters long (a simple protection against deleting everything in C:\ - I've been there and done that and it's not fun!!!)

这篇关于从目录中删除的文件,如果文件名包含某个词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆