-2

I am making a console application and from a particular folder I want to get only the images with specific extension.

Below code I am trying but it's retrieving all the files from the particular path.

string[] extensions = { ".jpg", ".jpeg", ".png", ".gif", ".tif" };
FileInfo[] files = new DirectoryInfo(SourcePath).GetFiles("*.*", SearchOption.AllDirectories);

How can I set extension on FileInfo[]?

Updated Issue

enter image description here

Answer

List<String> ImageFiles = Directory.GetFiles(SourcePath, "*.*",
             SearchOption.AllDirectories)
            .Where(file => new string[] { ".jpg", ".jpeg", ".png", ".gif", ".tif" }
            .Contains(Path.GetExtension(file)))
            .ToList();
            List<FileInfo> files = new List<FileInfo>();
            foreach (string filess in ImageFiles)
            {
                string replace = filess.Replace(@"\", "/");
                files.Add(new FileInfo(replace.Split('/').Last()));
            }

here how Can I get rid from for each loop as I am only needing file name and not the whole path

Mitesh Jain
  • 555
  • 4
  • 13
  • 40

3 Answers3

3

Please use the below code.

 List<String> ImageFiles = Directory.GetFiles(DirPath, "*.*",
                 SearchOption.AllDirectories)
                .Where(file => new string[] { ".jpg", ".jpeg", ".png", ".gif", ".tif" }
                .Contains(Path.GetExtension(file)))
                .ToList();
                List<FileInfo> images = new List<FileInfo>();
                foreach (string fileName in ImageFiles)
                {
                images.Add(new FileInfo(fileName));
                }
Aman Bachas
  • 264
  • 1
  • 6
2

Try following code snippet . Updated the answer as per your question

void Main()
{


List<string> ext = new List<string> { ".jpg", ".jpeg", ".png", ".gif", ".tif" }; 
FileInfo[] files = new DirectoryInfo(@"c:\temp").EnumerateFiles("*.*", SearchOption.AllDirectories) 
.Where(path => ext.Contains(Path.GetExtension(path.Name))) 
.Select(x => new FileInfo(x.FullName)).ToArray();
}

// Define other methods and classes here
santosh singh
  • 27,666
  • 26
  • 83
  • 129
2

I think it will be better to use Directory.EnumerateFiles instead of GetFiles. EnumerateFiles method is not waiting until all files are loaded. Which can be more efficient with large number of files.

void Main()
{
    string[] ext = new List<string> {".jpg", ".jpeg", ".png", ".gif", ".tif"};
    FileInfo[] files = new DirectoryInfo(SourcePath).EnumerateFiles(@"C:\temp", "*.*", SearchOption.AllDirectories)
     .Where(path => ext.Contains(Path.GetExtension(path.ToLower()));
}

UPDATE:

Answer to updated question.

    var ImageFilenames = Directory.EnumerateFiles(SourcePath, "*.*",
     SearchOption.AllDirectories)
    .Where(file => new string[] { ".jpg", ".jpeg", ".png", ".gif", ".tif" }
    .Contains(Path.GetExtension(file)))
    .Select(p => p.Substring(p.LastIndexOf('\\') + 1));
dropoutcoder
  • 2,627
  • 2
  • 14
  • 32