Coder Perfect

Using C# to get all file names from a folder [duplicate]

Problem

I’m curious if it’s feasible to acquire a list of all the names of text files in a specific folder.

For example, I have a folder called Maps, and I’d like to extract the names of all the text files in that folder and add them to a string list.

Is this possible, and if so, how do I go about doing it?

Asked by user2061405

Solution #1

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;
}

Answered by Gopesh Sharma

Solution #2

using System.IO; //add this namespace also 
string[] filePaths = Directory.GetFiles(@"c:\Maps\", "*.txt",
                                         SearchOption.TopDirectoryOnly);

Answered by Avitus

Solution #3

It is up to you to decide what you want to do.

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

All of the files in the chosen directory will be restored.

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

This will return ALL files with a specific extension in the supplied directory.

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

This will restore ALL files in the chosen directory, as well as all subdirectories with the specified extension.

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

Hope this helps

Answered by Gawie Greef

Solution #4

Does precisely what you’ve asked for.

System.IO.Directory.GetFiles

Answered by rerun

Solution #5

Take a peek at the Directory section. Method GetFiles (String, String) (MSDN).

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

Answered by James Culshaw

Post is based on https://stackoverflow.com/questions/14877237/getting-all-file-names-from-a-folder-using-c-sharp