Reputation: 23
For example: I want to know if there are images in a directory (eg. ".jpg") I want to return a boolean value that confirm whether there are files with that extension or not.
At first I started with the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Path1 As String
FolderBrowserDialog1.ShowDialog()
Path1 = FolderBrowserDialog1.SelectedPath
TextBox1.Text = FolderBrowserDialog1.SelectedPath 'ignore this
If System.IO.File.Exists(Path1 + "\*.jpg") = True Then
Label1.Text = "At least there is a .jpg"
End If
End Sub
It did not work and I thought use System.IO.Directory.GetFiles.The problem is how I can use it to give me back a value true / false, or rather to see if there is such file types
Upvotes: 1
Views: 568
Reputation: 43743
Private Function FileExists(folderPath As String, extension As String) As Boolean
Return (Directory.GetFiles(folderPath, "*." + extension).Length <> 0)
End Function
Upvotes: 0
Reputation: 564373
You can use Directory.EnumerateFiles along with Enumerable.Any:
Dim exists As Boolean = Directory.EnumerateFiles(folderName, "*.jpg").Any()
GetFiles
should also work (if you're in .NET 3.5), but will be less efficient:
Dim exists As Boolean = Directory.GetFiles(folderName, "*.jpg").Any()
Upvotes: 2