C# Exercise: 219 Sitemap creator

In this exercise, you need to create a program that displays the contents of a preliminary "sitemap" on the screen. The sitemap should be generated from the list of ".html" files in the current folder, with a "weekly" frequency and the current date as the "last modification" date. This exercise is useful for learning how to work with files in a directory and how to generate an XML file format that can be used by search engines like Google to improve a website's SEO. The program should loop through all the .html files, generate the appropriate sitemap tags, and display them on the console. You will learn to use classes such as Directory.GetFiles to retrieve files and File.GetLastWriteTime to get the modification date of each file.

 Exercise

Sitemap creator

 Objetive

A "sitemap" is a file that webmasters can use to inform Google about the webpages that their website includes, with the aim of achieving better search engine rankings.

You must create a program that displays the contents of a preliminary "sitemap" on the screen. The sitemap should be generated from the list of ".html" files in the current folder, with a "weekly" frequency and the current date as the "last modification" date.

 Example Code

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

class SitemapCreator
{
    // Main method where the program execution starts
    static void Main()
    {
        // Get the current date to use for "last modification" in the sitemap
        string currentDate = DateTime.Now.ToString("yyyy-MM-dd"); // Format date as yyyy-MM-dd

        // Write the XML declaration and opening  tag for the sitemap
        Console.WriteLine("");
        Console.WriteLine("");

        // Get all the .html files in the current directory
        string[] htmlFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.html");

        // Loop through each HTML file and generate a URL entry in the sitemap
        foreach (var file in htmlFiles)
        {
            // Get the file name (without the full path) to be used in the  tag
            string fileName = Path.GetFileName(file);

            // Write the  entry for the sitemap with location, frequency, and last modification date
            Console.WriteLine("  ");
            Console.WriteLine($"    {fileName}");  // File location
            Console.WriteLine("    weekly");  // Frequency is weekly
            Console.WriteLine($"    {currentDate}");  // Last modification date
            Console.WriteLine("  ");
        }

        // Write the closing  tag for the sitemap
        Console.WriteLine("");
    }
}