C# Exercise: 222 Sitemap creator v2

In this exercise, you need to create a program that takes three parameters: the name of a text file containing the URLs, the modification date, and the change frequency. The program should generate a sitemap based on the provided data. The text file should contain a list of file names to be indexed, with each file name on a separate line. The program should read the text file, process the URLs, and generate a sitemap with the specified dates and frequencies in the proper format for search engine use. This exercise will help you work with text files, handle command line parameters, and generate content based on those parameters.

 Exercise

Sitemap creator v2

 Objetive

You need to create a program that takes the following parameters: the name of a text file containing the URLs, the modification date, and the change frequency.

Example: sitemapCreator urls.txt 2011-11-18 weekly

The text file should contain a list of file names to be indexed, with each file name on a separate line.

 Example Code

// Import necessary namespaces
using System;
using System.IO;
using System.Text;

class SitemapCreator
{
    // Main method where the program execution starts
    static void Main(string[] args)
    {
        // Check if the correct number of arguments is provided
        if (args.Length != 3)
        {
            Console.WriteLine("Usage: sitemapCreator   ");
            return;
        }

        // Get the parameters from the command line arguments
        string urlsFile = args[0];
        string modificationDate = args[1];
        string changeFrequency = args[2];

        // Check if the file exists
        if (!File.Exists(urlsFile))
        {
            Console.WriteLine("The specified file does not exist.");
            return;
        }

        // Read URLs from the file
        string[] urls = File.ReadAllLines(urlsFile);

        // Prepare the sitemap content
        StringBuilder sitemap = new StringBuilder();
        sitemap.AppendLine("");
        sitemap.AppendLine("");

        // Add each URL to the sitemap
        foreach (string url in urls)
        {
            sitemap.AppendLine("  ");
            sitemap.AppendLine($"    {url}");
            sitemap.AppendLine($"    {modificationDate}");
            sitemap.AppendLine($"    {changeFrequency}");
            sitemap.AppendLine("  ");
        }

        sitemap.AppendLine("");

        // Define the output file name
        string outputFile = "sitemap.xml";

        // Write the sitemap content to the file
        try
        {
            File.WriteAllText(outputFile, sitemap.ToString());
            Console.WriteLine($"Sitemap created successfully! The file is saved as {outputFile}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while writing the sitemap: {ex.Message}");
        }
    }
}