选中文件夹中的多个文件存在

时间:2014-09-20 09:58:42

标签: 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, "File is Found")
    End If

如何更改代码以便同时检查多个文件?

2 个答案:

答案 0 :(得分:1)

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

只有一个:

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

答案 1 :(得分:-1)

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

 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