Exercise
TXT To HTML Translator
Objective
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.
Write Your C# Exercise
C# Exercise Example
// Import the System namespace for basic functionality
using System;
// Import the IO namespace for file handling
using System.IO;
// Create the class to handle text to HTML conversion
class TextToHtmlConverter
{
// Main method where the program starts
static void Main(string[] args)
{
// Ask the user for the source text file path
Console.WriteLine("Enter the path of the text file:");
// Get the file path from the user
string filePath = Console.ReadLine();
// Check if the file exists
if (File.Exists(filePath))
{
// Get the name of the file without extension
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
// Create the destination HTML file path by replacing the .txt extension with .html
string htmlFilePath = filePath.Replace(".txt", ".html");
try
{
// Open the source text file and read all lines
string[] lines = File.ReadAllLines(filePath);
// Open the destination HTML file to write the content
using (StreamWriter writer = new StreamWriter(htmlFilePath))
{
// Write the HTML structure, starting with the and tags
writer.WriteLine("");
writer.WriteLine("");
writer.WriteLine($"{fileNameWithoutExtension}"); // Title taken from the file name
writer.WriteLine("");
writer.WriteLine("");
// Write each line from the text file as a paragraph in the HTML body
foreach (string line in lines)
{
writer.WriteLine($"{line}
");
}
// Close the body and html tags
writer.WriteLine("");
writer.WriteLine("");
}
// Inform the user that the conversion was successful
Console.WriteLine("The text file has been successfully converted to HTML.");
}
catch (Exception ex) // Catch any errors that may occur
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
else
{
// Inform the user if the file does not exist
Console.WriteLine("The specified file does not exist.");
}
}
}