C# Exercise: 217 Display executable files in directory

In this exercise, you need to create a program that shows the names of all executable files (.com, .exe, .bat, .cmd) in the current folder, excluding the full path. The program should identify executable files in the directory where it is run and display only their names, without the folders containing them.

This exercise will allow you to practice filtering files when reading the file system in C#, enabling you to select and display only the files that match specific criteria.

Through this exercise, you will learn how to work with file extensions and how to retrieve only executable files, as well as how to manipulate strings to show only the file names.

 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)
        }
    }
}