List All Files And Subdirectories In A Directory With C#

In this article, I will discuss that how to get all files and subdirectories list from a directory.

Below is the C# code

using System;
using System.IO;

namespace FilesListFromDirectory
{
    class Program
    {
        static void Main(string[] args)
        {
            string MainDir = @"D:\";

            // get all files
            Console.WriteLine("Files in this directory.");
            Console.WriteLine("---------------------------------------------------------------------------------------");
            string[] Files = Directory.GetFiles(MainDir);
            Console.WriteLine(String.Join(Environment.NewLine, Files));

            Console.WriteLine("");

            // get all directories
            Console.WriteLine("Directories in this directory.");
            Console.WriteLine("---------------------------------------------------------------------------------------");
            string[] Directories = Directory.GetDirectories(MainDir);
            Console.WriteLine(String.Join(Environment.NewLine, Directories));
            Console.ReadKey();
        }
    }
}

Explanation

Here, in the above code, I’m using the GetFiles() method to get all files from the parent directory, and the GetDirectories() method is used to get all subdirectories from the parent directory.

Output

 

Submit a Comment

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

Subscribe

Select Categories