TXT to HTML translator Learn programming C# Sharp

Lesson:

File Management


Exercise:

TXT to HTML translator 42


Objetive:

Create a "Text to HTML converter", which will read a source text file and create a HTML file from its contents. For example, if the file contains:

Hola
Soy yo
Ya he terminado

The name of the destination file must be the same as the source file, but with ".html" extension (which will replace the original ".txt" extension, if it exists). The "title" in the "head" must be taken from the file name.


Code:

using System;
using System.IO;
namespace TXTtoHTML
{
    class Program
    {
        static void Main()
        {
            Console.Write("Enter name of file: ");
            string nameFileTxt = Console.ReadLine();
            string nameFileHtml = nameFileTxt.Substring(0, nameFileTxt.Length - 4);

            if (File.Exists(nameFileTxt))
            {
                StreamReader myfileTxt;
                StreamWriter myfileHtml;

                myfileTxt = File.OpenText(nameFileTxt);
                myfileHtml = File.CreateText(nameFileHtml + ".html");
                string line;

                myfileHtml.WriteLine("");
                myfileHtml.WriteLine("");
                myfileHtml.WriteLine("" + nameFileHtml + "");
                myfileHtml.WriteLine("");
                myfileHtml.WriteLine("");
                do
                {
                    line = myfileTxt.ReadLine();
                    if (line != null)
                        myfileHtml.WriteLine("" + line + "");
                }
                while (line != null);

                myfileHtml.WriteLine("");
                myfileHtml.WriteLine("");

                myfileTxt.Close();
                myfileHtml.Close();
            }
        }
    }
}