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.
Example C# Exercise
Show C# Code
using System;
using System.IO;
using System.Text;
class SitemapCreator
{
static void Main(string[] args)
{
if (args.Length != 3)
{
Console.WriteLine("Usage: sitemapCreator ");
return;
}
string urlsFile = args[0];
string modificationDate = args[1];
string changeFrequency = args[2];
if (!File.Exists(urlsFile))
{
Console.WriteLine("The specified file does not exist.");
return;
}
string[] urls = File.ReadAllLines(urlsFile);
StringBuilder sitemap = new StringBuilder();
sitemap.AppendLine("");
sitemap.AppendLine("");
foreach (string url in urls)
{
sitemap.AppendLine(" ");
sitemap.AppendLine($" {url}");
sitemap.AppendLine($" {modificationDate}");
sitemap.AppendLine($" {changeFrequency}");
sitemap.AppendLine(" ");
}
sitemap.AppendLine("");
string outputFile = "sitemap.xml";
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}");
}
}
}
Output
Suppose the urls_file.txt contains the following URLs:
https://example.com/page1
https://example.com/page2
https://example.com/page3
And the parameters passed are:
modification_date: 2024-12-24
change_frequency: weekly
The generated sitemap.xml file will have the following content:
https://example.com/page1
2024-12-24
weekly
https://example.com/page2
2024-12-24
weekly
https://example.com/page3
2024-12-24
weekly
To Run the Program:
sitemapCreator.exe urls_file.txt 2024-12-24 weekly