Quickly obtain every file name in a directory with C#

A quick post today showing how we can obtain the file name for every file in a given directory using C#. This might be useful for any kit where reading every file, or every kind of file in a directory is needed - e.g. reading in various data files. In this weeks research work, I ended up splitting a large data file into small components for quicker computation (and easier readability during sanity checking). It wasn't until the operation was finished and I found I had over 60 files created that I realised that saving the file names for each file as they were created would have been advantageous. Saving them into a separate file would save me typing them in again when I come to read in the smaller files later.

Of course, typing out the file names for each file is neither quick (for this sample size which could have been much larger than it was) nor necessarily accurate - one mistake in one file name could cause run-time errors that might not be simple to solve without a second pair of eyes. So naturally, the best way forward is to have the computer obtain the file names for us instead and that's guaranteed to be as they are in the directory (at the time it's run anyway).

C# Code

Luckily in C# we have access to Linq to do quick queries for us, and access to the Directory with System.IO. Thus, we can do a simple for each loop as follows:

Code breakdown

The core component of this loop is the GetFiles method which comes from Directory - a member of System.IO - make sure you're using this or hard coding ('System.IO.Directory') this namespace. After providing the full path to where we want to search, we can also provide a filter to the search - in this case I only needed the file names of file which had the extension '.csv' - you can leave this blank to obtain all files, or provide your own extension as necessary for your work.

Leave a Reply

Your email address will not be published. Required fields are marked *