C# provides a lot of tools to make working with the local file system much easier. For example, recently I had to get a list of files that are in a given directory.
Luckily with C#, inside of the System.IO namespace is the Directory helper object. This object has a lot of static methods that you can easily call to get information about a file name, path, ect.
Calling the Directory.GetFiles() method will return a list of files, as an array of strings;
Example:
static void listFilesFromDirectory(string workingDirectory) { // get a list of files in a directory, // based upon a path that is passed into the function string[] filePaths = Directory.GetFiles(workingDirectory); foreach (string filePath in filePaths) { // use the foreach loop to go through the entire // array one element at a time write out // the full path and file name of each of the // elements in the array Console.WriteLine ( filePath ); } }
As you look at the above example, you can see that you are using an array to store the list of file names within the directory. As a personal habit, I use a plural form of a name for variables that are arrays, this is because they hold multiple elements.
We then use the foreach loop to go through each individual element of the array. A variable, the singular filePath, holds the name for a single file element. This method displays the file name, it’s extension, and the full directory path to the file.
A sample video has been created where you can see this in action:
Get a List of Files From a Directory Using C# was originally found on Access 2 Learn