I'm trying to enumerate and import a number of image files in a folder. My current code for counting the images is as follows -
Dim fullpath As String
fullpath = TxtPath.Text + "\"
Dim FileDirectory As New IO.DirectoryInfo(fullpath)
Dim FileJpg As IO.FileInfo() = FileDirectory.GetFiles("*.jpg")
Dim FileJpeg As IO.FileInfo() = FileDirectory.GetFiles("*.jpeg")
Dim FileGif As IO.FileInfo() = FileDirectory.GetFiles("*.gif")
Dim FileBmp As IO.FileInfo() = FileDirectory.GetFiles("*.bmp")
Dim FilePng As IO.FileInfo() = FileDirectory.GetFiles("*.png")
Dim count As Integer = 0
For Each File As IO.FileInfo In FileJpg
count += 1
Next
For Each File As IO.FileInfo In FileJpeg
count += 1
Next
For Each File As IO.FileInfo In FileGif
count += 1
Next
For Each File As IO.FileInfo In FileBmp
count += 1
Next
For Each File As IO.FileInfo In FilePng
count += 1
Next
Is there a more efficient way to do this in one For loop, rather than the 5 separate ones - can you send an array of file extensions to GetFiles?
I'm also planning to use this code to import these images into a database, so having one loop would be much more efficient there too.
Thanks!
Not the best solution, but I don't have time for LINQ right now. Try this:
Dim extensions As New List(Of String)
extensions.Add("*.png")
' And so on, until all are in...
Dim fileCount As Integer
For i As Integer = 0 To extensions.Count - 1
fileCount += Directory.GetFiles(txtPath.Text, extensions(i), SearchOption.AllDirectories).Length
Next