vb.net 如何从文件夹中删除特定类型的所有文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25429791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:05:20  来源:igfitidea点击:

How do I delete all files of a particular type from a folder

.netvb.net

提问by Dipojjal

I'm using the following code for deleting all the files in a particular folder:

我正在使用以下代码删除特定文件夹中的所有文件:

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

Calling function:

调用函数:

DeleteFilesFromFolder("C:\New Folder")

Now, I want to delete all the *.pdfdocuments from new folder. How can I delete only the *.pdffiles from the folder (including the sub-folders)?

现在,我想*.pdf从新文件夹中删除所有文档。如何仅删除*.pdf文件夹(包括子文件夹)中的文件?

回答by Tasos K.

Directory.GetFiles()allows you to apply a search pattern and return you the files that match this pattern.

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

Check the MSDN link for more information: http://msdn.microsoft.com/en-us/library/wz42302f%28v=vs.110%29.aspx

查看 MSDN 链接以获取更多信息:http: //msdn.microsoft.com/en-us/library/wz42302f%28v=vs.110%29.aspx

回答by Nadeem_MK

You just have to check the extension before proceeding to deletion;

您只需要在继续删除之前检查扩展名;

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