Getting all file names from a folder using C#

C#ListText FilesDirectory

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

using System.IO; //add this namespace also 

string[] filePaths = Directory.GetFiles(@"c:\Maps\", "*.txt",
                                         SearchOption.TopDirectoryOnly);

Solution 3 - C#

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

Solution 4 - C#

Does exactly what you want.

System.IO.Directory.GetFiles

Solution 5 - C#

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

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

Solution 6 - C#

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.

Solution 7 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2061405View Question on Stackoverflow
Solution 1 - C#Gopesh SharmaView Answer on Stackoverflow
Solution 2 - C#AvitusView Answer on Stackoverflow
Solution 3 - C#Gawie GreefView Answer on Stackoverflow
Solution 4 - C#rerunView Answer on Stackoverflow
Solution 5 - C#James CulshawView Answer on Stackoverflow
Solution 6 - C#RainbowFishView Answer on Stackoverflow
Solution 7 - C#CompiledIOView Answer on Stackoverflow