Exercise
Extended Texttohtml (Files)
Objective
Expand the TextToHtml class, so that ir can dump it result to a text file. Create a method ToFile, which will receive the name of the file as a parameter.
Hint: You must use a "StreamWriter"
Write Your C# Exercise
C# Exercise Example
// Importing necessary namespaces for collections and file handling
using System;
using System.Collections.Generic;
using System.IO;
public class TextToHTML
{
// Declaring a list to store multiple strings entered by the user
private List textLines;
// Constructor to initialize the list
public TextToHTML()
{
textLines = new List();
}
// Method to add a new line of text to the list
public void Add(string text)
{
textLines.Add(text);
}
// Method to display all contents in the list to the console
public void Display()
{
foreach (string line in textLines)
{
Console.WriteLine(line); // Printing each line in the list
}
}
// Method to return all lines as a single string, separated by "\n"
public override string ToString()
{
return string.Join("\n", textLines); // Concatenating all lines with newline separators
}
// Method to write all lines to a specified file
public void ToFile(string fileName)
{
// Using StreamWriter to write to the specified file
using (StreamWriter writer = new StreamWriter(fileName))
{
foreach (string line in textLines)
{
writer.WriteLine(line); // Writing each line to the file
}
}
// Confirming that the content has been written to the file
Console.WriteLine("Content successfully written to file: " + fileName);
}
}
// Auxiliary class for testing the TextToHTML functionality
public class Program
{
public static void Main()
{
// Creating an instance of TextToHTML
TextToHTML textToHtml = new TextToHTML();
// Adding multiple lines of text to the instance
textToHtml.Add("Hello");
textToHtml.Add("This is a test");
textToHtml.Add("Final line");
// Displaying the contents on the console
Console.WriteLine("Displaying text on screen:");
textToHtml.Display();
// Writing the content to a file
textToHtml.ToFile("output.html"); // Specify the desired file name here
}
}