2014-09-20 79 views
2

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

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 

我该如何更改代码以便在同一时间检查多个文件?

+0

您是否有要检查的文件数组? – 2014-09-20 10:00:54

+0

nope ..现在,我只想如果两个文件存在..我甚至尝试此代码 如果File.Exists(“C:\ FINAL.txt”)= False和File.Exists(“C:\ FIRST.txt“)= False然后 – user2364790 2014-09-20 10:03:21

+0

这两个文件名都是一样的,如果你把第二个改成SECOND.txt或者什么的,它应该可以正常工作。 – 2014-09-20 10:06:17

回答

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 
+0

谢谢!有用。只是一个简单的问题。如果两个文件都存在,并且我想提示msgbox表示两个文件都存在,那么我该怎么做? MsgBox(“存在于系统文件夹中的文件”,MsgBoxStyle.Information,“File is Found”) – user2364790 2014-09-20 10:50:05

-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 
+0

我可以这样做,但之后的问题是如果文件目录包含太多的文件?以及如何检查第二个文件是否存在? – user2364790 2014-09-20 10:23:31

相关问题