Getting all file names from a folder using C#
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;
}
Solution 2
using System.IO; //add this namespace also
string[] filePaths = Directory.GetFiles(@"c:\Maps\", "*.txt",
SearchOption.TopDirectoryOnly);
Solution 3
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
Does exactly what you want.
Solution 5
Take a look at Directory.GetFiles Method (String, String) (MSDN).
This method returns all the files as an array of filenames.
Related videos on Youtube
Comments
-
user2061405 almost 2 years
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?
-
James Culshaw over 11 yearsMuch more efficient to use the inbuilt GetFiles method on the Directory class.
-
Jeff over 9 yearsUsing System.IO;
-
Jared Wadsworth over 9 yearsFileInfo has a lot of overhead, it would be much better to use Path.GetFileName(filePath)
-
Aaron Franke over 5 yearsHow does
Directory.GetFiles
compare to theDirectoryInfo
andFileInfo
approach? -
Aaron Franke over 5 yearsHow does
DirectoryInfo
andFileInfo
compare to theDirectory.GetFiles
approach? -
Aaron Franke over 5 years
IO
is capitalized. -
Pona over 5 years@AaronFranke
Directory.GetFiles
will give you an array of fullpaths of the files contained in the Directory, whereas theDirectoryInfo
approach will give you an array ofFileInfo
, which contains more info about each file, such as filename, extension, size, modified time, etc. -
the_lone_note over 4 yearsAround here we discourage simply linking to the manual. Next time you should also paste in the relevant information with your answer here.
-
arsdever about 3 years@Jeff Please be under some answers, where it's not obvious which namespaces are used :D Thx.