294

I wanted to know if it is possible to get all the names of text files in a certain folder.

For example, I have a folder with the name Maps, and I would like to get the names of all the text files in that folder and add it to a list of strings.

Is it possible, and if so, how I can achieve this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user2061405
  • 3,141
  • 3
  • 14
  • 9

7 Answers7

465
using System.IO;

DirectoryInfo d = new DirectoryInfo(@"D:\Test"); //Assuming Test is your Folder

FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
string str = "";

foreach(FileInfo file in Files )
{
  str = str + ", " + file.Name;
}
Halo
  • 1,730
  • 1
  • 8
  • 31
Gopesh Sharma
  • 6,730
  • 4
  • 25
  • 35
207
using System.IO; //add this namespace also 

string[] filePaths = Directory.GetFiles(@"c:\Maps\", "*.txt",
                                         SearchOption.TopDirectoryOnly);
Hammad Sajid
  • 312
  • 1
  • 3
  • 14
Avitus
  • 15,640
  • 6
  • 43
  • 53
  • 3
    How does `Directory.GetFiles` compare to the `DirectoryInfo` and `FileInfo` approach? – Aaron Franke Dec 06 '18 at 22:16
  • 8
    @AaronFranke `Directory.GetFiles` will give you an array of fullpaths of the files contained in the Directory, whereas the `DirectoryInfo` approach will give you an array of `FileInfo`, which contains more info about each file, such as filename, extension, size, modified time, etc. – Pona Dec 16 '18 at 19:29
88

It depends on what you want to do.

ref: http://www.csharp-examples.net/get-files-from-directory/

This will bring back ALL the files in the specified directory

string[] fileArray = Directory.GetFiles(@"c:\Dir\");

This will bring back ALL the files in the specified directory with a certain extension

string[] fileArray = Directory.GetFiles(@"c:\Dir\", "*.jpg");

This will bring back ALL the files in the specified directory AS WELL AS all subdirectories with a certain extension

string[] fileArray = Directory.GetFiles(@"c:\Dir\", "*.jpg", SearchOption.AllDirectories);

Hope this helps

Gawie Schneider
  • 1,078
  • 1
  • 9
  • 14
17

Does exactly what you want.

System.IO.Directory.GetFiles

rerun
  • 25,014
  • 6
  • 48
  • 78
8

Take a look at Directory.GetFiles Method (String, String) (MSDN).

This method returns all the files as an array of filenames.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
James Culshaw
  • 1,047
  • 8
  • 19
7

http://msdn.microsoft.com/en-us/library/system.io.directory.getfiles.aspx

The System.IO namespace has loads of methods to help you with file operations. The

Directory.GetFiles() 

method returns an array of strings which represent the files in the target directory.

thesheps
  • 635
  • 4
  • 11
-10

I would recommend you google 'Read objects in folder'. You might need to create a reader and a list and let the reader read all the object names in the folder and add them to the list in n loops.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CompiledIO
  • 160
  • 16