Sitemap creator Learn programming with C# Sharp exercises

Lesson:

Additional Libraries


Exercise:

Sitemap creator 57


Objetive:

A "sitemap" is a file that webmasters can use in order to tell Google the webpages that their site consists on, and get a better positioning in the search engine.

Yo must create a program to show on screen the contents of a preliminary "sitemap", taken from the list of ".html" files in the current directory, with "weekly" frequence and the current date as "last modification" date.


Code:

using System;
using System.Collections.Generic;
using System.IO;
class SitemapCreator
{
    static void Main()
    {
        List ListHtml = GetHtml();

        CreateSiteMap(ListHtml, "weekly", DateTime.Now);
    }


    static void CreateSiteMap(List listHtml, string frecuency, DateTime lastUpdated)
    {
        try
        {
            StreamWriter writer = new StreamWriter(File.Create("sitemap.xml"));

            writer.WriteLine("");
            writer.WriteLine("");

            foreach (string html in listHtml)
            {
                writer.WriteLine("");
                writer.WriteLine("" + html + "");
                writer.WriteLine("" + lastUpdated.ToShortDateString() + "");
                writer.WriteLine("" + frecuency + "");
                writer.WriteLine("");
            }

            writer.WriteLine("");

            writer.Close();
        }
        catch
        {
            Console.WriteLine("Error writing sitemap.");
        }
    }

    static List GetHtml()
    {
        List ListHtml = new List();

        string[] files = Directory.GetFiles(".");

        foreach (string file in files)
        {
            string extension = Path.GetExtension(file);

            switch (extension)
            {
                case ".html":
                case ".htm":
                    ListHtml.Add(file.Substring(2));
                    break;
            }
        }

        return ListHtml;
    }
}