110

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.

Samuel Rondeau-Millaire
  • 1,100
  • 2
  • 13
  • 24
Dominic K
  • 6,975
  • 11
  • 53
  • 62

6 Answers6

218

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");
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
  • Thanks! All the answers were good, but you answered first so... yeah :) – Dominic K Jun 30 '10 at 18:37
  • 7
    This doesn't work if the extension would be something like txt_. I'm trying to determine if there are any *.exe file in a folder, and I only have one *.exe_ file, but the query returns it, which is not correct. – Adrian Jan 25 '13 at 11:20
  • 1
    The Documentation: https://msdn.microsoft.com/en-us/library/8he88b63(v=vs.110).aspx – Randall Flagg Feb 24 '15 at 12:51
  • What if I want the single file who's named like `macos.txt` – Prashant Pimpale Oct 09 '18 at 06:12
  • I want to find all the files without any extension. I have some files with file type "file" (no extension), how can I find those files? – sohaiby Mar 20 '19 at 07:25
  • 2
    To search recursively, call the overload with `SearchOption.AllDirectories`. Something like this: `string[] files = System.IO.Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);`. (This is covered in other answers, but not this accepted answer.) – srk Apr 26 '21 at 19:00
42

You could use the Directory class

 Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories)
sgriffinusa
  • 4,203
  • 1
  • 25
  • 26
  • 3
    This doesn't work if the extension would be something like txt_ or anything else as stated in the documentation https://msdn.microsoft.com/en-us/library/wz42302f(v=vs.110).aspx – Randall Flagg Feb 24 '15 at 12:50
  • @RandallFlagg, I read the docs, disagree. There are special cases, 8.3 naming, longfilenames etc. *.txt and *.txt_ should be found. Look at the docs where they talk about 8.3 and xls and xlsx extensions – t.durden Sep 02 '21 at 13:04
14

It's quite easy, actually. You can use the System.IO.Directory class in conjunction with System.IO.Path. Something like (using LINQ makes it even easier):

var allFilenames = Directory.EnumerateFiles(path).Select(p => Path.GetFileName(p));

// Get all filenames that have a .txt extension, excluding the extension
var candidates = allFilenames.Where(fn => Path.GetExtension(fn) == ".txt")
                             .Select(fn => Path.GetFileNameWithoutExtension(fn));

There are many variations on this technique too, of course. Some of the other answers are simpler if your filter is simpler. This one has the advantage of the delayed enumeration (if that matters) and more flexible filtering at the expense of more code.

Greg D
  • 43,259
  • 14
  • 84
  • 117
  • Thanks for all the extra work you put into this. However, I'm just going for a simple statement since I only have one text file in the directory (it was extracted by my program). – Dominic K Jun 30 '10 at 18:29
3

The method below returns only the files with certain extension (eg: file with .txt but not .txt1)

public static IEnumerable<string> GetFilesByExtension(string directoryPath, string extension, SearchOption searchOption)
    {
        return
            Directory.EnumerateFiles(directoryPath, "*" + extension, searchOption)
                .Where(x => string.Equals(Path.GetExtension(x), extension, StringComparison.InvariantCultureIgnoreCase));
    }
hazjack
  • 1,645
  • 13
  • 27
1

As per my understanding, this can be done in two ways :

1) You can use Directory Class with Getfiles method and traverse across all files to check our required extension.

Directory.GetFiles("your_folder_path)[i].Contains("*.txt")

2) You can use Path Class with GetExtension Method which takes file path as a parameter and verifies the extension.To get the file path, just have a looping condition that will fetch a single file and return the filepath that can be used for verification.

Path.GetExtension(your_file_path).Equals(".json")

Note : Both the logic has to be inside a looping condition.

Pulkit Shah
  • 81
  • 1
  • 10
0

Use this code for read file with all type of extension file.

string[] sDirectoryInfo = Directory.GetFiles(SourcePath, "*.*");