Vb.net 检查文件夹中是否存在多个文件

Vb.net 检查文件夹中是否存在多个文件,vb.net,directory,Vb.net,Directory,我想检查文件夹中的几个文件。如果逐个检查文件,我没有问题。目前,我有这个代码只检查一个文件 If File.Exists("C:\FINAL.txt") = False Then MsgBox("Field does not exist!", MsgBoxStyle.Critical, "File Not Found") Else MsgBox("File Exist in System Folder", MsgBoxStyle.Information

我想检查文件夹中的几个文件。如果逐个检查文件,我没有问题。目前,我有这个代码只检查一个文件

  If File.Exists("C:\FINAL.txt") = False Then
        MsgBox("Field does not exist!", MsgBoxStyle.Critical, "File Not Found")
    Else
        MsgBox("File Exist in System Folder", MsgBoxStyle.Information, "File is Found")
    End If

如何更改代码,使其同时检查多个文件

您可以通过以下查询检查目录中的所有文件,并查找所需文件是否存在:

 Dim dir As DirectoryInfo = New DirectoryInfo("d:\")
 dim flag As Integer=0
 For Each File As FileInfo In dir.GetFiles
    If File.Name = "FINAL.txt" Then
        MsgBox("File Exist in System Folder", MsgBoxStyle.Information, "File is Found") 
        flag=1 
    End If
 Next
 If flag = 0 Then
    MsgBox("File does not Exist in System Folder", MsgBoxStyle.Information, "File not Found") 
 End

有很多方法可以做到这一点

只有一个:

Public Class Form1

    Private Shadows Sub Load() Handles MyBase.Load

        Dim Files As String() = {"C:\File1.txt", "C:\File2.txt"}

        For Each File As String In Me.CheckFileExists(Files)

            MessageBox.Show(String.Format("File doesn't exist: {0}", File), "File Not Found",
                            MessageBoxButtons.OK, MessageBoxIcon.Error)

        Next File

    End Sub

    Private Function CheckFileExists(ByVal Files As IEnumerable(Of String)) As IEnumerable(Of String)

        Dim sb As New System.Text.StringBuilder

        For Each File As String In Files

            If Not IO.File.Exists(File) Then
                sb.AppendLine(File)
            End If

        Next File

        Return sb.ToString.Split({Environment.NewLine},
                                 StringSplitOptions.RemoveEmptyEntries)

    End Function

End Class

您有要检查的文件数组吗?没有。。现在,我只想知道其中两个文件是否存在。。如果File.Exists(“C:\FINAL.txt”)=False和File.Exists(“C:\FIRST.txt”)=False,我甚至会尝试这段代码。然后这两个文件名都是相同的,如果您将第二个文件名更改为
second.txt
或其他内容,它应该可以正常工作。您根本不应该编写这样的代码。File.Exists()只是告诉您该文件在一微秒前就存在了。当你需要它存在的时候,它不会保证它仍然存在。多任务操作系统的危险。这类错误很难诊断,也不会经常出错。否则就完全不清楚为什么不能使用数组和For循环。我尝试更改文件名,但代码只检查第一个文件,而忽略第二个文件。我可以这样做,但之后的问题是,如果文件目录包含太多文件怎么办?如何检查第二个文件是否存在?谢谢!!它起作用了。就一个简单的问题。如果两个文件都存在,并且我想提示msgbox说这两个文件都存在,我该怎么做?MsgBox(“文件存在于系统文件夹中”,MsgBoxStyle.Information,“文件已找到”)