Directory.GetAllImageFiles How should i do it?

2.4k views Asked by At

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"?

2

There are 2 answers

2
Lasse Espeholt On BEST ANSWER

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.

0
Gary Kindel On

This is 2.0 .net solution.

I did something similar in C#. This solution used an folder as a drop off point for images to be processed. Loading each type of file as an image is not correct solution in all cases but I wanted to validate each file as a loadable image.

    string[] files = Directory.GetFiles(folderPath);
    foreach(string file in files)
    {


        System.Drawing.Image img = null;

        try
        {
            img = System.Drawing.Image.FromFile(file);
        }
        catch
        {
            // do nothing
        }

        if (img != null)
        {
            // did something

            img.Dispose();
        }
    }

Turns out I forgot a piece... Before I process the files, I did use a function to limit files being processed:

private bool IsImage(FileInfo file)
{
    bool imageFile = false;
    if ((file.Extension.ToLower() ==".jpg")||
       (file.Extension.ToLower() ==".gif")||
       (file.Extension.ToLower() == ".bmp") ||
       (file.Extension.ToLower() ==".png"))
    {
        imageFile = true;
    }

    return imageFile;
}