Home > DeveloperSection > Forums > How to search for only jpg files in a directory using c#?
Jeet Verma
Jeet Verma

Total Post:110

Points:776
Posted on    March-17-2015 6:30 AM

 .NET C#  Winforms 
Ratings:


 1 Reply(s)
 470  View(s)
Rate this:

I want to search a directory and get the list of all jpg files. The code that I have is as follow:

string[] fileList = Directory.Exists(this._imageDirectory)

                                            ? Directory.GetFiles(this._imageDirectory, "*.jpg")

                                            : null;

This is working well if I have files such as below:

1.jpg

2.jpg

3.txt

In the above case it finds only two files. But if I have the following files:

1.jpg

2.jpg

3.jpg_tmp

it finds 3 files. It finds 3.jpg_tmp which it should not find it.

How can I fix it without looking into all fileList and finding the ones that are not correct?



Ankita Pandey
Ankita Pandey

Total Post:183

Points:1285
Posted on    March-17-2015 7:19 AM

You can filter the list with LINQ:

var pictures = fileList != null ?

        fileList.Where(name => name.EndsWith(".jpg")).ToArray() :

        Enumerable.Empty<string>().ToArray();


Don't want to miss updates? Please click the below button!

Follow MindStick