Programming Course in C# ¡Free!

Extended TextToHTML (files)

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

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"

Output



Solution


using System;
using System.IO;

class TextToHTML
{
private string[] html;
private int lines;
private int count;

public TextToHTML()
{
count = 0;
lines = 1000;

html = new string[lines];
}

public void ToFile(string nameFile) 
{
try 
{ 
StreamWriter file = File.CreateText(nameFile);
file.WriteLine( ToString() );
file.Close();
}
catch (Exception e) 
{
Console.WriteLine("Error!!!");
}
}

public void Add(string line)
{
if (count < lines)
{
html[count] = line;
count++;
}
}

public string ToString()
{
string textHtml;

textHtml = "\n";
textHtml += "\n";

for (int i = 0; i < count; i++)
{
textHtml += "

"; textHtml += html[i]; textHtml += "

\n"; } textHtml += "\n"; textHtml += "\n"; return textHtml; } public void Display() { Console.Write( ToString() ); } } class Test { static void Main() { TextToHTML textToHTML = new TextToHTML(); textToHTML.Add("Hello"); textToHTML.Add("How are you?"); textToHTML.Display(); textToHTML.ToFile("prueba.html"); } }