Read and Write Text Files With Visual Basic

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 5

Basic methods

Before we jump into working with text files, we need to create a new file or open an
existing one. That requires the System.IO.File class. This class contains methods for
many common file operations, including copying, deleting, file attribute manipulation,
and file existence. For our text file work, we will use the CreateText and OpenText
methods.

CreateText
True to its name, the CreateText method creates a text file and returns a
System.IO.StreamWriter object. With the StreamWriter object, you can then write to the
file. The following code demonstrates how to create a text file:
Dim oFile as System.IO.File
Dim oWrite as System.IO.StreamWriter
oWrite = oFile.CreateText(“C:\sample.txt”)
OpenText

The OpenText method opens an existing text file for reading and returns a
System.IO.StreamReader object. With the StreamReader object, you can then read the
file. Let’s see how to open a text file for reading:
Dim oFile as System.IO.File
Dim oRead as System.IO.StreamReader
oRead = oFile.OpenText(“C:\sample.txt”)

Writing to a text file


The methods in the System.IO.StreamWriter class for writing to the text file are Write
and WriteLine. The difference between these methods is that the WriteLine method
appends a newline character at the end of the line while the Write method does not. Both
of these methods are overloaded to write various data types and to write formatted text to
the file. The following example demonstrates how to use the WriteLine method:
oWrite.WriteLine(“Write a line to the file”)
oWrite.WriteLine() ‘Write a blank line to the file

Formatting the output


The Write and WriteLine methods both support formatting of text during output. The
ability to format the output has been significantly improved over previous versions of
Visual Basic. There are several overloaded methods for producing formatted text. Let’s
look at one of these methods:
oWrite.WriteLine(“{0,10}{1,10}{2,25}”, “Date”, “Time”, “Price”)
oWrite.WriteLine(“{0,10:dd MMMM}{0,10:hh:mm tt}{1,25:C}”, Now(), 13455.33)
oWrite.Close()

The overloaded method used in these examples accepts a string to be formatted and then
a parameter array of values to be used in the formatted string. Let’s look at both lines
more carefully.

The first line writes a header for our report. Notice the first string in this line is {0,10}
{1,10}{2,25}. Each curly brace set consists of two numbers. The first number is the index
of the item to be displayed in the parameter array. (Notice that the parameter array is zero
based.) The second number represents the size of the field in which the parameter will be
printed. Alignment of the field can also be defined; positive values are left aligned and
negative values are right aligned.
The second line demonstrates how to format values of various data types. The first field
is defined as {0,10:dd MMMM}. This will output today’s date (retrieved using the Now()
function) in the format 02 July. The second field will output the current time formatted as
02:15 PM. The third field will format the value 13455.33 into the currency format as
defined on the local machine. So if the local machine were set for U.S. Dollars, the value
would be formatted as $13,455.33.

Listing A shows the output of our sample code.

Reading from a text file


The System.IO.StreamReader class supports several methods for reading text files and
offers a way of determining whether you are at the end of the file that's different from
previous versions of Visual Basic.

Line-by-line
Reading a text file line-by-line is straightforward. We can read each line with a ReadLine
method. To determine whether we have reached the end of the file, we call the Peek
method of the StreamReader object. The Peek method reads the next character in the file
without changing the place that we are currently reading. If we have reached the end of
the file, Peek returns -1. Listing B provides an example for reading a file line-by-line
until the end of the file.

An entire file
You can also read an entire text file from the current position to the end of the file by
using the ReadToEnd method, as shown in the following code snippet:
Dim EntireFile as String
oRead = oFile.OpenText(“C:\sample.txt”)
EntireFile = oRead.ReadToEnd()

This example reads the file into the variable EntireFile. Since reading an entire file can
mean reading a large amount of data, be sure that the string can handle that much data.

One character at a time


If you need to read the file a character at a time, you can use the Read method. This
method returns the integer character value of each character read. Listing C demonstrates
how to use the Read method.
Listing A
Date Time Price
22 July 10:58 AM $13,455.33

Listing B
oRead = oFile.OpenText(“C:\sample.txt”)

While oRead.Peek <> -1


LineIn = oRead.ReadLine() ’LineIn je label ili textbox

End While

oRead.Close()

Listing C
Dim intSingleChar as Integer

Dim cSingleChar as String

oRead = oFile.OpenText(“C:\sample.txt”)

While oRead.Peek <> -1

intSingleChar = oRead.Read()

‘ Convert the integer value into a character

cSingleChar = Chr(intSingleChar)

End While

http://articles.techrepublic.com.com/5100-10878_11-1045309.html#

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button2.Click
'upis reda u fajl Primer sa unapred odredjenim definicijama
Dim oFile As System.IO.File
Dim oWrite As System.IO.StreamWriter
oWrite = oFile.CreateText("C:\Primer.txt")

'Dim oRead As System.IO.StreamReader


' oRead = oFile.OpenText("C:\Primer.txt")

' oWrite.WriteLine("{0,10}{1,10}{2,25}", "Date", "Time",


"Price")
'oWrite.WriteLine("{0,10:dd MMMM}{0,10:hh:mm tt}{1,25:C}",
Now(), 13455.33)
'oWrite.WriteLine("{0,10}{1,10}", "X", "Y")
oWrite.WriteLine(LH.Text())
oWrite.WriteLine(LW.Text())

oWrite.Close()

End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button3.Click
' kod cita fajl Primer ispisuje sadrzaj prve linije na textbox1
Dim oFile As System.IO.File
Dim oRead As System.IO.StreamReader

oRead = oFile.OpenText("C:\Primer.txt")

Label9.Text = oRead.ReadLine()
Label10.Text = oRead.ReadLine()
TextBox1.Text = oRead.ReadLine()
oRead.Close()

' kod broji koliko se nalazi reci u textbox1, razmak uzima kao
jednu rec
Dim i, CountWord As Integer
For i = 1 To Len(TextBox1.Text)
If Mid(TextBox1.Text, Len(TextBox1.Text) - (i - 1), 1) <> "
" And i <> Len(TextBox1.Text) Then
Else
CountWord = CountWord + 1
End If

Next
MsgBox("There are " & CountWord & " words", MsgBoxStyle.OkOnly)

'kod cita svaki karaktet fajla posebno dok nedodje do kraja,


ali ih neispisuje na ekranu
Dim intSingleChar As Integer
Dim cSingleChar As String
oRead = oFile.OpenText("C:\Primer.txt")
While oRead.Peek <> -1
intSingleChar = oRead.Read()

cSingleChar = Chr(intSingleChar)

End While
'Deljenje stringa na dva dela radi!!!
' We want to split this input string
Dim s As String = TextBox1.Text

' Split string based on spaces


Dim words As String() = s.Split(New Char() {" "c})

' Dim words As String() = s.Split(New Char() {" "c})


' Use For Each loop over words and display them
Dim word As String
For Each word In words
Console.WriteLine(word)
' Label9.Text = word
' Label10.Text = word.Length - 1
' pozabaviti se ovim
Next
End Sub

You might also like