首页 > 解决方案 > For Each Loop in VB.net 卡在条件语句中

问题描述

我正在尝试使用 vb.net 编写代码,但我陷入了一个For Each循环,我希望有人能提供帮助。

我正在尝试按扩展名搜索文件,我使用了For Each如下循环:

For Each XMLLFILE In Directory.GetFiles(directoryName, "*.xmll", SearchOption.TopDirectoryOnly)

之后,我尝试添加一个条件来删除搜索到的文件,如果没有,则弹出一条消息,指出没有找到文件。其余的代码是:

    If My.Computer.FileSystem.FileExists(XMLLFILE) Then
        File.Delete(XMLLFILE)
        MsgBox("Files Deleted !", vbOKOnly, "DeleteXMLL Files")
    Else
        MsgBox("There's No files to be Deleted !", vbOKOnly, "DeleteXMLL Files")
    End If
    Exit For
Next
End If

每次删除文件(重复)时,我都会收到一个消息框,如果文件夹内没有文件,我根本没有消息框。

任何人都可以帮助代码吗?

标签: vb.net

解决方案


GetFiles()方法返回该文件夹中确实存在的文件。您的If语句检查每个文件是否存在,这没有意义(因为我们已经知道它们存在)。相反,您应该检查是否GetFiles()返回任何文件。

尝试以下操作:

' Find the files and store them in a String array.
Dim filesToDelete As String() = 
    Directory.GetFiles(directoryName, "*.xmll", SearchOption.TopDirectoryOnly)

' If some files are found,...
If filesToDelete.Any() Then
    ' Delete each one of them...
    For Each XMLLFILE In filesToDelete
        File.Delete(XMLLFILE)
    Next
    ' ..and then display a success message.
    MsgBox("Files Deleted!", vbOKOnly, "DeleteXMLL Files")
Else
    ' If not, display a different message.
    MsgBox("There are No files to be Deleted!", vbOKOnly, "DeleteXMLL Files")
End If

推荐阅读