Programming Course in C# ¡Free!

TXT to HTML translator

 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise

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 resulting HTML file should contain

Example

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.

Output



Solution


using System;
using System.IO;

class TXTtoHTML
{
static void Main()
{
Console.Write("Enter name of file: ");
string nameTXT = Console.ReadLine();
string nameHTML = nameTXT.Substring(0, nameTXT.Length - 4);

if (File.Exists(nameTXT)) 
{
StreamReader fileTXT = File.OpenText(nameTXT);
StreamWriter fileHTML = File.CreateText(nameHTML + ".html");

fileHTML.WriteLine("");
fileHTML.WriteLine("");
fileHTML.WriteLine("" + nameHTML + "");
fileHTML.WriteLine("");
fileHTML.WriteLine("");

string line;
do
{
line = fileTXT.ReadLine();
if (line != null)
fileHTML.WriteLine("

" + line + "

"); } while (line != null); fileHTML.WriteLine(""); fileHTML.WriteLine(""); fileTXT.Close(); fileHTML.Close(); } }