Display Executable Files in Current Folder in C#

In this exercise, you will create a C# program that retrieves and displays the names of all executable files in the current folder. The program will search for files with specific extensions: .com, .exe, .bat, and .cmd. This exercise helps you practice file manipulation, filtering based on file extensions, and working with directories in C#.



Group

Using Additional Libraries in C#

Objective

1. Use the System.IO namespace for file and directory operations.
2. Retrieve all files in the current directory using Directory.GetFiles.
3. Filter the files to only include .com, .exe, .bat, and .cmd extensions.
4. Loop through the filtered files and display just their names (excluding the full path).
5. Display each matching file name to the console.

Create a program that shows the names (excluding the path) of all executable files (.com, .exe, .bat, .cmd) in the current folder.

Example C# Exercise

 Copy C# Code
using System;  // Importing the System namespace for basic functionalities
using System.IO;  // Importing the System.IO namespace for file and directory operations

class Program
{
    static void Main()
    {
        // Get the current directory path
        string currentDirectory = Directory.GetCurrentDirectory();
        
        // Retrieve all files in the current directory with specific extensions
        string[] files = Directory.GetFiles(currentDirectory, "*.com");

        // Add additional file types to search for
        files = files.Concat(Directory.GetFiles(currentDirectory, "*.exe")).ToArray();
        files = files.Concat(Directory.GetFiles(currentDirectory, "*.bat")).ToArray();
        files = files.Concat(Directory.GetFiles(currentDirectory, "*.cmd")).ToArray();

        // Display the executable files to the console (excluding path)
        Console.WriteLine("Executable files in the current directory:");

        // Loop through each file and display only the file name (excluding the path)
        foreach (string file in files)
        {
            string fileName = Path.GetFileName(file);  // Extracting the file name from the full path
            Console.WriteLine(fileName);  // Display the file name
        }

        // Wait for user input before closing the program
        Console.ReadKey();
    }
}

 Output

Executable files in the current directory:
program1.exe
script.bat
tool.com
launcher.cmd

Share this C# Exercise

More C# Practice Exercises of Using Additional Libraries in C#

Explore our set of C# Practice Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.