Extended TextToHTML (files) Learn programming Visual Basic (VB.net)

Lesson:

File Management


Exercise:

Extended TextToHTML (files)


Objetive:

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"


Code:

Imports System
Imports System.IO
Class TextToHTML
    Private html As String()
    Private lines As Integer
    Private count As Integer

    Public Sub New()
        count = 0
        lines = 1000
        html = New String(lines - 1) {}
    End Sub

    Public Sub ToFile(ByVal nameFile As String)
        Try
            Dim file As StreamWriter = File.CreateText(nameFile)
            file.WriteLine(ToString())
            file.Close()
        Catch e As Exception
            Console.WriteLine("Error!!!")
        End Try
    End Sub

    Public Sub Add(ByVal line As String)
        If count < lines Then
            html(count) = line
            count += 1
        End If
    End Sub

    Public Function ToString() As String
        Dim textHtml As String
        textHtml = vbLf
        textHtml += vbLf

        For i As Integer = 0 To count - 1
            textHtml += ""
            textHtml += html(i)
            textHtml += vbLf
        Next

        textHtml += vbLf
        textHtml += vbLf
        Return textHtml
    End Function

    Public Sub Display()
        Console.Write(ToString())
    End Sub
End Class

Class Test
    Private Shared Sub Main()
        Dim textToHTML As TextToHTML = New TextToHTML()
        textToHTML.Add("Hello")
        textToHTML.Add("How are you?")
        textToHTML.Display()
        textToHTML.ToFile("prueba.html")
    End Sub
End Class

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.