Text File Processing

Question:

“Text File Processing” Please respond to the following:

Visual Basic provides libraries that allow data to be read from a text file into a program. Once the data is read from the file, it can be processed in a number ways. Assume you are a developer working for a small retail company. You have been asked to develop a Visual Basic application that reads product information from a file and generates a report. The input file contains many lines of product data: Each line contains product identification, name, price, and quantity. Explain the process you would use to generate the report.

A program that requires data from a text file will fail if there is a problem with the text file: file may not be accessible, file may be empty, or there may not be enough system memory to process the file. What would you do in your program to avoid these pitfalls when working with text file in your program?

The TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs. The TextFieldType property defines whether it is a delimited file or one with fixed-width fields of text.

To parse a comma delimited text file

Create a new TextFieldParser. The following code creates the TextFieldParser named MyReader and opens the file test.txt.

Using MyReader As New Microsoft.VisualBasic.

FileIO.TextFieldParser(

“C:TestFoldertest.txt”)

Define the TextField type and delimiter. The following code defines the TextFieldType property as Delimited and the delimiter as “,”.

MyReader.TextFieldType = FileIO.FieldType.Delimited

MyReader.SetDelimiters(“,”)

Loop through the fields in the file. If any lines are corrupt, report an error and continue parsing. The following code loops through the file, displaying each field in turn and reporting any fields that are formatted incorrectly.

Dim currentRow As String()

While Not MyReader.EndOfData

Try

currentRow = MyReader.ReadFields()

Dim currentField As String

For Each currentField In currentRow

MsgBox(currentField)

Next

Catch ex As Microsoft.VisualBasic.

FileIO.MalformedLineException

MsgBox(“Line ” & ex.Message &

“is not valid and will be skipped.”)

End Try

Close the While and Using blocks with End While and End Using.

End While

End Using

Example

This example reads from the file test.txt.

Using MyReader As New Microsoft.VisualBasic.

FileIO.TextFieldParser(

“C:TestFoldertest.txt”)

MyReader.TextFieldType = FileIO.FieldType.Delimited

MyReader.SetDelimiters(“,”)

Dim currentRow As String()

While Not MyReader.EndOfData

Try

currentRow = MyReader.ReadFields()

Dim currentField As String

For Each currentField In currentRow

MsgBox(currentField)

Next

Catch ex As Microsoft.VisualBasic.

FileIO.MalformedLineException

MsgBox(“Line ” & ex.Message &

“is not valid and will be skipped.”)

End Try

End While

End Using

Write a text file (example 2)

The following code uses the StreamWriter class to open, to write to, and to close the text file. Unlike the previous example, this code passes two additional parameters to the constructor.

The first parameter is the file path and file name of the file. The second parameter, True, specifies that the file be opened in append mode. If you specify False for the second parameter, the contents of the file are overwritten each time you run the code. The third parameter specifies Unicode so that StreamWriter encodes the file in Unicode. You can also specify the following encoding methods for the third parameter:

ASCII

BigEndianUnicode

UTF7

UTF8

The Write method is similar to the WriteLine method except that Write does not automatically embed a carriage return/line feed (CR/LF) character combination. This is useful when you want to write one character at a time.

Start Visual Studio 2005 or Visual Studio .NET.

Create a new Console Application in Visual Basic 2005 or Visual Basic .NET.

Add the following code to the top of Module1.vb:

Imports System.IO

Imports System.Text

Add the following code to the Sub Main procedure under your existing code:

Dim objStreamWriter As StreamWriter

Dim x As Long

‘Open the file.

objStreamWriter = New StreamWriter(“C:Test2.txt”, True, _

Encoding.Unicode)

‘Write out the numbers 1 through 10 on the same line.

For x = 1 To 10

objStreamWriter.Write(x)

Next x

‘Close the file.

objStreamWriter.Close()

On the Debug menu, click Start to compile and to run the application.

This code creates a file that is named Test2.txt on drive C. Open Test2.txt in a text editor such as Notepad. Test2.txt contains a single line of text:

12345678910

Note If you run the code several times, the “123456789” text is repeated on the same line.

Complete code listing

‘Read a Text File

Imports System.IO

Module Module1

Sub Main()

Dim objStreamReader As StreamReader

Dim strLine As String

‘Pass the file path and the file name to the StreamReader constructor.

objStreamReader = New StreamReader(“C:Boot.ini”)

‘Read the first line of text.

strLine = objStreamReader.ReadLine

‘Continue to read until you reach the end of the file.

Do While Not strLine Is Nothing

‘Write the line to the Console window.

Console.WriteLine(strLine)

‘Read the next line.

strLine = objStreamReader.ReadLine

Loop

‘Close the file.

objStreamReader.Close()

Console.ReadLine()

End Sub

End Module

‘Write a Text File: Version 1

Imports System.IO

Module Module1

Sub Main()

Dim objStreamWriter As StreamWriter

‘Pass the file path and the file name to the StreamWriter constructor.

objStreamWriter = New StreamWriter(“C:Text.txt”)

‘Write a line of text.

objStreamWriter.WriteLine(“Hello World”)

‘Write a second line of text.

objStreamWriter.WriteLine(“From the StreamWriter class”)

‘Close the file.

objStreamWriter.Close()

End Sub

End Module

‘Write a Text File: Version 2

Imports System.IO

Imports System.Text

Module Module1

Sub Main()

Dim objStreamWriter As StreamWriter

Dim x As Long

‘Open the file.

objStreamWriter = New StreamWriter(“C:Test2.txt”, True, _

Encoding.Unicode)

‘Write out the numbers 1 through 10 on the same line.

For x = 1 To 10

objStreamWriter.Write(x)

Next x

‘Close the file.

objStreamWriter.Close()

End Sub

End Module

Troubleshooting

Whenever you input or output a file, it is good programming practice to wrap the code inside a Try-End-Try block in case an error occurs. Some possible errors include a file that does not exist, or a file that is already in use.

Robust Programming

The following conditions may cause an exception:

A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line causing the exception, while the ErrorLine property is assigned the text contained in the line.

The specified file does not exist (FileNotFoundException).

A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).

The path is too long (PathTooLongException).

The user does not have sufficient permissions to access the file (UnauthorizedAccessException).

Place an Order

Plagiarism Free!

Scroll to Top