41

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.

Ercan
  • 2,699
  • 10
  • 53
  • 60

10 Answers10

44

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();
dtb
  • 213,145
  • 36
  • 401
  • 431
  • 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. https://github.com/faisalmansoor/MiscUtil/blob/master/EnumFiles/Program.cs – Faisal Mansoor Aug 19 '13 at 21:10
32

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);
Rui Caramalho
  • 455
  • 8
  • 16
Marek Bar
  • 873
  • 3
  • 16
  • 31
11

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);
}
Jirka Picek
  • 589
  • 5
  • 19
Olena Vikariy
  • 217
  • 1
  • 3
  • 9
5

I found the solution this Might work

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

You need the recursive form of GetFiles:

DirectoryInfo.GetFiles(pattern, searchOption);   

(specify AllDirectories as the SearchOption)

Here's a link for more information:

MSDN: DirectoryInfo.GetFiles

dreadwail
  • 15,098
  • 21
  • 65
  • 96
3

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);
KMier
  • 81
  • 1
  • 3
2

GetFiles("*.jpg", SearchOption.AllDirectories) has a problem at windows7. If you set the directory to c:\users\user\documents\, then it has an exception: because of windows xp, win7 has links like Music and Pictures in the Documents folder, but theese folders don't really exists, so it creates an exception. Better to use a recursive way with try..catch.

weiszam
  • 187
  • 4
  • 14
2

You can use GetFiles

GetFiles("*.jpg", SearchOption.AllDirectories)
volody
  • 6,946
  • 3
  • 42
  • 54
1

This will get list of all images from folder and sub folders and it also take care for long file name exception in windows.

// To handle long folder names Pri external library is used.
// Source https://github.com/peteraritchie/LongPath    
using Directory = Pri.LongPath.Directory;
using DirectoryInfo = Pri.LongPath.DirectoryInfo;
using File = Pri.LongPath.File;
using FileInfo = Pri.LongPath.FileInfo;
using Path = Pri.LongPath.Path;

// Directory and sub directory search function
 public void DirectoryTree(DirectoryInfo dr, string searchname)
        {
            FileInfo[] files = null;
            var allFiles = new List<FileInfo>();
            try
            {
                files = dr.GetFiles(searchname);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            if (files != null)
            {
                try
                {
                    foreach (FileInfo fi in files)
                    {
                        allFiles.Add(fi);

                        string fileName = fi.DirectoryName + "\\" + fi.Name;
                        string orgFile = fileName;
                    }
                    var subDirs = dr.GetDirectories();

                    foreach (DirectoryInfo di in subDirs)
                    {
                        DirectoryTree(di, searchname);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

            }
        }

   public List<String> GetImagesPath(String folderName)
    {
       var dr = new DirectoryInfo(folderName);
       string ImagesExtensions = "jpg,jpeg,jpe,jfif,png,gif,bmp,dib,tif,tiff";
       string[] imageValues = ImagesExtensions.Split(',');
       List<String> imagesList = new List<String>();

                foreach (var type in imageValues)
                {
                    if (!string.IsNullOrEmpty(type.Trim()))
                    {
                        DirectoryTree(dr, "*." + type.Trim());
                        // output to list 
                       imagesList.Add = DirectoryTree(dr, "*." + type.Trim());
                    }

                }
         return imagesList;
  }
-1
var files = new DirectoryInfo(path).GetFiles("File")
    .OrderByDescending(f => f.LastWriteTime).First();

This could gives you the perfect result of searching file with its latest mod

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135