如果文件名包含特定单词,则从目录中删除文件
我需要检查一个目录,看看是否有文件名包含特定关键字的文件,如果有,则将其删除。这可能吗?
例如,删除“C:\Folder
”中文件名包含关键字“Apple”的所有现有文件。
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?
For example, delete all existing files in "C:\Folder
" whose file name contains the keyword "Apple".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
要扩展 Henk 的答案,您需要:
非常小心!
请注意,我已经注释掉了删除命令。运行它并仔细测试它,然后让它真正删除任何内容!
如果您希望递归删除根文件夹的所有子文件夹中的文件,请添加 ,System.IO.SearchOption.AllDirectories);到 GetFiles 调用。
如果您这样做,如果 rootFolderPath 的长度小于大约 4 个字符,则拒绝运行也是一个非常的好主意(一个简单的保护措施,防止删除 C:\ 中的所有内容 - 我已经去过那里并且这样做了,这并不好玩!)
To expand on Henk's answer, you need:
BE VERY CAREFUL!
Note that I've commented out the delete command. Run it and test it carefully before you let it actually delete anything!
If you wish to recursively delete files in ALL subfolders of the root folder, add ,System.IO.SearchOption.AllDirectories); to the GetFiles call.
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!!!)
您可以使用 System.IO.Directory.GetFiles() 获取 string[] 格式的文件列表。
<罢工>
然后,您可以使用 System.IO.File.ReadAllText() 读取完整文件,或者如果文件很大,请使用 System.IO.File.OpenText() 打开 TextReader代码>.
如果您正在寻找文字关键字,
String.Contains()
就是您所需要的。可以使用 System.IO.File.Delete() 来删除文件。确保文件再次关闭。
编辑,
GetFiles()
的 2 个示例:You can use
System.IO.Directory.GetFiles()
to a list of the files, in string[] format.Then you can use
System.IO.File.ReadAllText()
to read complete files, or if they are very big, open a TextReader withSystem.IO.File.OpenText()
.If you are looking for a literal keyword,
String.Contains()
is all you need.Deleting a file can be done with
System.IO.File.Delete()
. Make sure the file is closed again.Edit, 2 examples of
GetFiles()
:或者
or
或多或少,这个:
More or less, this: