In this blog post, we will have a look at how we can get all files from a specified directory using C#.

C# gives us a really handy in-built method from which we can read a directory and it's information.

First, we will make use of the DirectoryInfo class. We will instantiate a new DirectoryInfo class and provide the directory path from which we want to get the files.

Then, using the directoryInfo variable, we will access all the files using the GetFiles method.

Let's see this in action with an example:

var directory = new DirectoryInfo("STRING_PATH_OF_DIRECTORY"); var files = directory.GetFiles(); foreach (var file in files) { // Iterate on files and access all the information of the file // file.Delete(); // file.CopyTo("NEW_FILE_PATH_WITH_FILE_NAME"); // file.Name // file.FullName // file.Length }

 

Getting Specific File Types Using GetFiles Method

The GetFiles method on the DirectoryInfo class gives us a way to search and retrieve specific file types.

You can use a search pattern and provide this to the GetFiles method as the first parameter and it will get all files matching that search criteria.

Example:

var directory = new DirectoryInfo("STRING_PATH_OF_DIRECTORY"); var files = directory.GetFiles("*.txt"); // Get all txt files