Display executable files in directory C# Exercise - C# Programming Course

 Exercise

Display executable files in directory

 Objetive

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

 Example Code

// Import the System.IO namespace which provides methods for working with files and directories
using System;
using System.IO;

class Program
{
    // Main method to execute the program
    static void Main()
    {
        // Get the current directory where the program is running
        string currentDirectory = Directory.GetCurrentDirectory();  // Retrieves the current working directory

        // Display the message to the user about executable files in the current directory
        Console.WriteLine("Executable files in the current directory:");

        // Get all executable files (.exe, .com, .bat, .cmd) in the current directory
        string[] executableFiles = Directory.GetFiles(currentDirectory, "*.*") // Get all files in the directory
            .Where(file => file.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) || // Check if file ends with .exe
                           file.EndsWith(".com", StringComparison.OrdinalIgnoreCase) || // Check if file ends with .com
                           file.EndsWith(".bat", StringComparison.OrdinalIgnoreCase) || // Check if file ends with .bat
                           file.EndsWith(".cmd", StringComparison.OrdinalIgnoreCase)) // Check if file ends with .cmd
            .ToArray(); // Convert the filtered result into an array

        // Loop through and display each executable file
        foreach (string file in executableFiles)
        {
            Console.WriteLine(Path.GetFileName(file));  // Display only the file name (no path)
        }
    }
}

Juan A. Ripoll - Programming Tutorials and Courses © 2025 All rights reserved.  Legal Conditions.