How to list all files in a folder in C#

C# program to list all files in a folder:

There are different ways to list all files in a folder in C#. We can list all files, files with specific extension, all files in the subfolders etc. This is pretty easy in C#. In this post, I will show you how to do all of these with examples. Let’s code.

Get all files in a folder:

To get all files in a folder, use the below program:

using System;
using System.IO;

namespace c_sharp
{
    class Program
    {
        static void Main(string[] args)
        {

            string path = @"C:\Users\cvc\Desktop";

            string[] files = Directory.GetFiles(path);

            foreach (string file in files)
            {
                Console.WriteLine(file);
            }
        }
    }
}

Here, we are using Directory.GetFiles to get all files in the given path. It returns one array of strings and we are storing that in files.

Next, we are running one foreach to print all files in the string arrary files. If you run this program, it will print all file paths in the given path.

C:\Users\cvc\Desktop\song.mp3
C:\Users\cvc\Desktop\file.pdf     
C:\Users\cvc\Desktop\NewFolder

Note that this program also prints the folders and files in that given path. But, it will not print the files in the inner folders.

Get all files with a specific extension:

No, we don’t have to filter out the array that Directory.GetFiles returns. We can pass the extension that we need for the files as the second parameter to Directory.GetFiles and it will return all files in that path with that particular extension.

Suppose, we want all .mp3 files in a directory. The below program will do that:

using System;
using System.IO;

namespace c_sharp
{
    class Program
    {
        static void Main(string[] args)
        {

            string path = @"C:\Users\cvc\programs";

            string[] files = Directory.GetFiles(path, "*.mp3");

            foreach (string file in files)
            {
                Console.WriteLine(file);
            }
        }
    }
}

It will return all file paths with .mp3 extension.

We can pass different types of search pattern for the second parameter. For example, if we want all files starts with e, we can pass e* as the second parameter.

Get all files in the current directory and its subdirectories:

To get all files in the current directory and also in its sub directories, we need to use * as the second parameter and SearchOption.AllDirectories as the third parameter. It will return all files in all directories.

using System;
using System.IO;

namespace c_sharp
{
    class Program
    {
        static void Main(string[] args)
        {

            string path = @"C:\Users\cvc\programs";

            string[] files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);

            foreach (string file in files)
            {
                Console.WriteLine(file);
            }
        }
    }
}

You might also like: