DEV Community

Cover image for Get the list of all files with specific extension in C#
KOTESWAR RAO MEESALA
KOTESWAR RAO MEESALA

Posted on

Get the list of all files with specific extension in C#

One might have come across a situation to fetch all the files under a given directory and do something with those files. In this article, we will look at how it can be done with a single line of code in C#. Later, I'm going to mention how did I stumble upon such a use case.

We will be using GetFiles static method available on Directory class under System.IO namespace. This method has three overloads. We will use the one that takes three arguments.

  • A string that takes an absolute or relative path to the directory
  • A string that takes a search pattern to match the files against
  • A search option to search recursively or only the current directory

Alt Text

My use case is to search for all the images with a .bmp extension under the specified directory and convert them to jpeg images.
So, the line of code I would use is

Directory.GetFiles(@"C:\mydir", "*.bmp", SearchOption.AllDirectories);

Here, SearchOption is an enum that contains two fields. AllDirectories and TopDirectoryOnly. I guess it's self-explanatory how to use those fields.
Make sure when you are using AllDirectories, the directory structure do not form a loop.

That's it!! I hope this article has augmented that knowledge bundle of yours.

Thank you!! Happy to receive feedback and answer any questions !!

Top comments (0)