Sitemap creator Learn programming C#



Lesson:

Additional Libraries


Exercise:

Sitemap creator


Objetive:

A "sitemap" is a file that webmasters can use to inform Google about the webpages that their website includes, with the aim of achieving better search engine rankings.

You must create a program that displays the contents of a preliminary "sitemap" on the screen. The sitemap should be generated from the list of ".html" files in the current folder, with a "weekly" frequency and the current date as the "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;
    }
}



Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.