我正在使用以下代码删除特定文件夹中的所有文件:
Sub DeleteFilesFromFolder(Folder As String)
If Directory.Exists(Folder) Then
For Each _file As String In Directory.GetFiles(Folder)
File.Delete(_file)
Next
For Each _folder As String In Directory.GetDirectories(Folder)
DeleteFilesFromFolder(_folder)
Next
End If
End Sub
通话功能:
DeleteFilesFromFolder("C:\New Folder")
现在,我想删除新文件夹中的所有*.pdf
文档。如何仅从文件夹(包括子文件夹)中删除*.pdf
个文件?
答案 0 :(得分:12)
Directory.GetFiles()
允许您应用搜索模式并返回与此模式匹配的文件。
Sub DeleteFilesFromFolder(Folder As String)
If Directory.Exists(Folder) Then
For Each _file As String In Directory.GetFiles(Folder, "*.pdf")
File.Delete(_file)
Next
For Each _folder As String In Directory.GetDirectories(Folder)
DeleteFilesFromFolder(_folder)
Next
End If
End Sub
查看MSDN链接以获取更多信息:http://msdn.microsoft.com/en-us/library/wz42302f%28v=vs.110%29.aspx
答案 1 :(得分:2)
您必须先检查扩展程序才能继续删除;
Sub DeleteFilesFromFolder(Folder As String)
If Directory.Exists(Folder) Then
For Each _file As String In Directory.GetFiles(Folder)
If System.IO.Path.GetExtension(_file) = ".pdf" Then ' Check extension
File.Delete(_file)
End If
Next
For Each _folder As String In Directory.GetDirectories(Folder)
DeleteFilesFromFolder(_folder)
Next
End If
End Sub