Published on: 11 Jan, 2019

A simple way to get all files in a folder and subfolders in c#.

Tumblr Digg Google Plus

If you want to get all files from a folder and subfolder, you can easily use the built-in function from System.IO namespace. Here is a sample code on how to get all the files and return it as an array of FileInfo object. The following code is written in a console application program. Let's review the code

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace bytutorial.com.getfilesexample
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo objDirectoryInfo = new DirectoryInfo(@"C:\ExampleFolder");
            FileInfo[] allFiles = objDirectoryInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly);
            FileInfo[] javascriptFiles = objDirectoryInfo.GetFiles("*.js", SearchOption.AllDirectories);

            foreach(var file in allFiles)
            {
                Console.WriteLine("File: " + file.Name + ", Full Path: " + file.FullName);
            }

            Console.ReadLine();
        }
    }
}

The first thing to remember before we start, is to import the System.IO namespace. Once you have imported the namespace, we can use DirectoryInfo keyword to create a Directory object. From the Directory object, we can use the built-in function called GetFiles. The GetFiles function has 3 different parameters acceptance. Here is the list.

  • 1. No parameters or empty void function.

    This one will only get all files from the current directory.

  • 2. One parameter with search patern.

    This will still get all files from the current directory. You can use specific pattern to prform files search. For example if you only to search for javascript files like above code example, you can just need to pass a string with value *.js

  • 3. Two parameter with search patern and option to include all subfolders.

    This will be the same as the second option, the only difference is you be able to specify whether you want to include search options only or top parent directory only.

Download Files

You can download the files on the following link.

Download

Hopefully this simple tutorial helps. If you have any question, feel free to post your comment below.

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.