Extended Texttohtml (Files) - C# Programming Exercise

In this exercise of C#, you need to expand the TextToHtml class so that it can dump its result to a text file. You should create a ToFile method that takes the file name as a parameter and uses a StreamWriter to write the generated content into the file. This exercise is an excellent opportunity to learn how to work with output streams in C#, specifically for saving data to a text file. The ToFile method must ensure that the file is created or overwritten properly and handle potential errors, such as writing permissions or file non-existence.

Through this exercise, the programmer will learn how to manipulate files in C#, with a focus on writing HTML content generated by the program. This skill is useful in many applications, such as generating dynamic reports or exporting data to files.

 Category

File Management

 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

// 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
    }
}

 Share this C# exercise

 More C# Programming Exercises of File Management

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  Logger

    In this exercise of C#, you need to create a Logger class with a static Write method, which will append a certain text to a log file. The method should ...

  •  More

    In this exercise of C#, you need to create a program that behaves like the Unix "more" command. The program should display the contents of a text file and prom...

  •  Text replacer

    In this exercise of C#, you need to create a program to replace words in a text file, saving the result into a new file. The program should take as parameters the fil...

  •  Count letters in a file

    In this exercise of C#, you need to create a program to count how many times a specific character appears inside a file of any kind. The file and the letter to search...

  •  Reading a binary file (1: BMP)

    In this exercise of C#, you need to create a program that checks if a BMP image file seems to be correct. The program must verify if the first two bytes of the file ...

  •  Writing to a binary file

    In this exercise of C#, you need to create a program that asks the user for their name, age (as a byte), and the year they were born (as an int), and st...