Ejercicio
Conversor De TXT A HTML
Objectivo
Cree un "convertidor de texto a HTML", que leerá un archivo de texto de origen y creará un archivo HTML a partir de su contenido. Por ejemplo, si el archivo contiene:
Hola
Soy yo
Ya he terminado
El nombre del archivo de destino debe ser el mismo que el archivo de origen, pero con la extensión ".html" (que reemplazará a la extensión ".txt" original, si existe). El "título" en el "encabezado" debe tomarse del nombre del archivo.
Ejemplo Ejercicio C#
Mostrar Código C#
// 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.");
}
}
}
Salida
If the user has a text file named example.txt with the following content:
Hello, this is a sample text file.
It will be converted to HTML.
If the file path entered is incorrect or the file doesn't exist, the program will display:
The specified file does not exist.
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp