Programming Course in C# ¡Free!

12.06 - Sitemap creator

 Saturday, April 06, 2013 published by Exercises C#

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.


Its basic appearance is:



<?xml version="1.0" encoding="utf-8"?> 


<url>

<lastmod>2013-03-18</lastmod>
<changefreq>daily</changefreq>
</url>
<url>
<lastmod>2013-03-18</lastmod>
<changefreq>weekly</changefreq>
</url>
</urlset> 



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.



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;
    }
}