Find a file with a certain extension in folder

Dominic K picture Dominic K · Jun 30, 2010 · Viewed 146.9k times · Source

Given a folder path (like C:\Random Folder), how can I find a file in it that holds a certain extension, like txt? I assume I'll have to do a search for *.txt in the directory, but I'm not sure how I'm supposed to start this search in the first place.

Answer

Anthony Pegram picture Anthony Pegram · Jun 30, 2010

Look at the System.IO.Directory class and the static method GetFiles. It has an overload that accepts a path and a search pattern. Example:

 string[] files = System.IO.Directory.GetFiles(path, "*.txt");