List of images as HTML C# Exercise - C# Programming Course

 Exercise

List of images as HTML

 Objetive

Create a program that creates an HTML file that lists all the images (PNG and JPG) in the current folder.

For instance, if the current folder contains the following images:

1.png
2.jpg

 Example Code

// Import the necessary namespaces for working with file and string operations
using System;
using System.IO;

class ListImagesAsHTML
{
    // Main method where the program execution starts
    static void Main()
    {
        // Get all the image files (PNG and JPG) in the current directory
        string[] imageFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.*")
                                      .Where(file => file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
                                                     file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase))
                                      .ToArray();

        // Create or open the HTML file to write the image list
        string htmlFilePath = "image_list.html";
        using (StreamWriter writer = new StreamWriter(htmlFilePath))
        {
            // Write the basic HTML structure
            writer.WriteLine("");
            writer.WriteLine("Image List");
            writer.WriteLine("");
            writer.WriteLine("

List of Images

"); writer.WriteLine("
    "); // Loop through each image file and add it to the HTML list foreach (var imageFile in imageFiles) { // Get the file name without the full path string fileName = Path.GetFileName(imageFile); // Add an
  • element for each image with the tag writer.WriteLine($"
  • \"{fileName}\"
  • "); } // Close the list and body tags writer.WriteLine("
"); writer.WriteLine(""); writer.WriteLine(""); } // Inform the user that the HTML file has been created Console.WriteLine($"HTML file created: {htmlFilePath}"); } }

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