C# Exercise: 220 List of images as HTML

In this exercise, you need to create a program that generates an HTML file listing all the images (PNG and JPG files) in the current folder. The program should search for image files in the directory and create an HTML file containing tags for each image found. This will help you learn how to work with files in a directory and create an HTML file dynamically using C# programming. This exercise also lets you practice handling and displaying images on a webpage easily. You will use functions like Directory.GetFiles to retrieve the images and write the HTML file using classes like StreamWriter.



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