Sitemap creator v2 Learn programming C#

Lesson:

Additional Libraries


Exercise:

Sitemap creator v2


Objetive:

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.


Code:

using System;
using System.IO;
using System.Collections.Generic;
class SitemapCreator2
{
    static void Main(string[] param)
    {
        if (param.Length != 3)
        {
            Console.WriteLine("Error number of params.");
            return;
        }

        string file = param[0];
        string date = param[1];
        string frecuency = param[2];

        List ListUrls = GetUrls(file);

        CreateSiteMap(ListUrls, frecuency, date);
    }


    static void CreateSiteMap(List listHtml, string frecuency, string 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 + "");
                writer.WriteLine("" + frecuency + "");
                writer.WriteLine("");
            }

            writer.WriteLine("");

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

    static List GetUrls(string nameFile)
    {
        try
        {
            StreamReader reader = new StreamReader(File.OpenRead(nameFile));
            string line = "";
            List urls = new List();

            do
            {
                line = reader.ReadLine();

                if (line != null)
                {
                    urls.Add(line);
                }
            }
            while (line != null);

            reader.Close();

            return urls;
        }
        catch
        {
            Console.WriteLine("Error reading file.");

            return null;
        }
    }
}

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