سؤال

I would like to get a list of all image files in a given folder.

Dim targetFolder As String = "C:\Data\"    
Dim imagefiles = From file In Directory.EnumerateFiles(targetFolder)

For Each f In imagefiles
    'do something
Next

The above lists however all file types. How to change it to return only image file types?

هل كانت مفيدة؟

المحلول

Image files could have multiple extensions, but EnumerateFiles could take only one extension in its overload. You could overcome this limitation providing a list of file extensions and using the IEnumerable methods Where and Any

Dim targetFolder As String = "C:\Data"    
Dim imgExtensions() As string  = { ".jpg", ".jpeg", ".bmp", ".gif", ".png" }
Dim imageFiles = Directory.EnumerateFiles(targetFolder) _ 
                 .Where(Function(s) imgExtensions _
                 .Any(Function(x) x = Path.GetExtension(s)))

For Each file in imageFiles
    Console.WriteLine(file)
Next

نصائح أخرى

Add a second parameter to Directory.EnumerateFiles:

Directory.EnumerateFiles(targetFolder, "*.jpg")

You can pass a second parameter to Directory.EnumerateFiles that is a search pattern:

Dim targetFolder As String = "C:\Data\"    
Dim imagefiles = From file In Directory.EnumerateFiles(targetFolder, "*.jpg")

For Each f In imagefiles
    'do something
Next

This will enumerate all files that end in .jpg. However, there is no definite list of "all image files". You will need to define that yourself in a search pattern that makes sense to your application.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top