views:

44

answers:

3

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 suppose to start this search in the first place.

EDIT: Thanks all! Works like a charm. Gotta hone my search skills :)

+2  A: 

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
Thanks! All the answers were good, but you answered first so... yeah :)
DMan
+2  A: 

You could use the Directory class

 Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories)
sgriffinusa
+1  A: 

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
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).
DMan