I would like to get fill a String array with all the images found within a directory.
Till now i use the following to get all the images with jpg format
Dim List() as string = Directory.GetFiles(Path, "*.jpg")
Now i would like to extend it and get all the image formats.
Could i use the directory.GetFiles combined with an "ImageFormat
enumeration"?
Hi you can use this which I found as community content at http://msdn.microsoft.com/en-us/library/wz42302f.aspx.:
private static string[] GetFiles(string sourceFolder, string filters)
{
return filters.Split('|').SelectMany(filter => System.IO.Directory.GetFiles(sourceFolder, filter)).ToArray();
}
an alternative which uses lazy evaluation (.Net 4.0 only):
private static IEnumerable<string> GetFiles(string sourceFolder, string filters)
{
return filters.Split('|').SelectMany(filter => System.IO.Directory.EnumerateFiles(sourceFolder, filter));
}
You can use it like GetFiles("dir", "*.jpg|*.gif|*.jpeg|*.bmp|*.png")
. It is essentially just a search for each filter, so it is not as efficient as it can get.
A final version is (is .Net 4.0 only, but can be made to a 2.0 solution at least):
private static IEnumerable<string> GetImageFiles(string sourceFolder)
{
return from file in System.IO.Directory.EnumerateFiles(sourceFolder)
let extension = Path.GetExtension(file)
where extension == ".jpg" || extension == ".gif" || extension == ".png"
select file;
}
I believe the last one is the fastest because it only loops once. But this depends on how the pattern search is implemented in Directory
and how the OS searches. A performance test is needed which I haven't done.