Exercise
Sitemap Creator V2
Objective
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.
Write Your C# Exercise
C# Exercise Example
// 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}");
}
}
}