2014-09-20 83 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

相關問題