Selasa, 21 Desember 2010

Read and write text files with Visual Basic .NET

CreateText

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()


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
oRead = oFile.OpenText(“C:\sample.txt”)

 While oRead.Peek <> -1
       LineIn = oRead.ReadLine()

 End While

 oRead.Close()
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() 
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
 

Tidak ada komentar:

Posting Komentar