C#:Getting all image files in folder

c#
93,042

Solution 1

Have a look at the DirectoryInfo.GetFiles overload that takes a SearchOption argument and pass SearchOption.AllDirectories to get the files including all sub-directories.

Another option is to use Directory.GetFiles which has an overload that takes a SearchOption argument as well:

return Directory.GetFiles(folderName, "*.*", SearchOption.AllDirectories)
                .ToList();

Solution 2

I'm using GetFiles wrapped in method like below:

 public static String[] GetFilesFrom(String searchFolder, String[] filters, bool isRecursive)
 {
    List<String> filesFound = new List<String>();
    var searchOption = isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
    foreach (var filter in filters)
    {
       filesFound.AddRange(Directory.GetFiles(searchFolder, String.Format("*.{0}", filter), searchOption));
    }
    return filesFound.ToArray();
 }

It's easy to use:

String searchFolder = @"C:\MyFolderWithImages";
var filters = new String[] { "jpg", "jpeg", "png", "gif", "tiff", "bmp", "svg" };
var files = GetFilesFrom(searchFolder, filters, false);

Solution 3

There's a good one-liner solution for this on a similar thread:

get all files recursively then filter file extensions with LINQ

Or if LINQ cannot be used, then use a RegEx to filter file extensions:

var files = Directory.GetFiles("C:\\path", "*.*", SearchOption.AllDirectories);

List<string> imageFiles = new List<string>();
foreach (string filename in files)
{
    if (Regex.IsMatch(filename, @"\.jpg$|\.png$|\.gif$"))
        imageFiles.Add(filename);
}

Solution 4

I found the solution this Might work

                foreach (string img in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),"*.bmp" + "*.jpg" + "SO ON"))

Solution 5

This allows you to use use the same syntax and functionality as Directory.GetFiles(path, pattern, options); except with an array of patterns instead of just one.

So you can also use it to do tasks like find all files that contain the word "taxes" that you may have used to keep records over the past year (xlsx, xls, odf, csv, tsv, doc, docx, pdf, txt...).

public static class CustomDirectoryTools {
    public static string[] GetFiles(string path, string[] patterns = null, SearchOption options = SearchOption.TopDirectoryOnly) {
        if(patterns == null || patterns.Length == 0)
            return Directory.GetFiles(path, "*", options);
        if(patterns.Length == 1)
            return Directory.GetFiles(path, patterns[0], options);
        return patterns.SelectMany(pattern => Directory.GetFiles(path, pattern, options)).Distinct().ToArray();
    }
}

In order to get all image files on your c drive you would implement it like this.

string path = @"C:\";
string[] patterns = new[] {"*.jpg", "*.jpeg", "*.jpe", "*.jif", "*.jfif", "*.jfi", "*.webp", "*.gif", "*.png", "*.apng", "*.bmp", "*.dib", "*.tiff", "*.tif", "*.svg", "*.svgz", "*.ico", "*.xbm"};
string[] images = CustomDirectoryTools.GetFiles(path, patterns, SearchOption.AllDirectories);
Share:
93,042
Ercan
Author by

Ercan

An analytical software developer with deep expertise in Java, SQL, IOS and Objective-C technologies posses 4+ year hands on experience, also interest on PHP, Python and Javascript. Focused on web and UI development. Also experienced on mobile application and mobile game development on IOS platform with Cocos framework. Versed in both agile and waterfall development techniques. Skilled in requirements analysis and project documentation. Able to communicate effectively with both technical and non-technical project stakeholders. Expertise in current and emerging trends and techniques. Proficient in coding and developing the new program.

Updated on July 16, 2021

Comments

  • Ercan
    Ercan almost 3 years

    I am trying to get all images from folder but ,this folder also include sub folders. like /photos/person1/ and /photos/person2/ .I can get photos in folder like

      path= System.IO.Directory.GetCurrentDirectory() + "/photo/" + groupNO + "/";
     public List<String> GetImagesPath(String folderName)
        {
    
            DirectoryInfo Folder;
            FileInfo[] Images;
    
            Folder = new DirectoryInfo(folderName);
            Images = Folder.GetFiles();
            List<String> imagesList = new List<String>();
    
            for (int i = 0; i < Images.Length; i++)
            {
                imagesList.Add(String.Format(@"{0}/{1}", folderName, Images[i].Name));
               // Console.WriteLine(String.Format(@"{0}/{1}", folderName, Images[i].Name));
            }
    
    
            return imagesList;
        }
    

    But how can I get all photos in all sub folders? I mean I want to get all photos in /photo/ directory at once.

  • Faisal Mansoor
    Faisal Mansoor over 10 years
    I usually prefer enumerating each directory manually rather than using SearchOption.AllDirectories, because with SearchOption.AllDirectories the complete call will fail if a UnauthorizedAccessException occur while enumerating a subfolder. github.com/faisalmansoor/MiscUtil/blob/master/EnumFiles/…