When you want to read data from a text file, you create a file object using the ____________.

Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

How to: Read From Text Files in Visual Basic

  • Article
  • 09/15/2021
  • 2 minutes to read

In this article

The ReadAllText method of the My.Computer.FileSystem object allows you to read from a text file. The file encoding can be specified if the contents of the file use an encoding such as ASCII or UTF-8.

If you are reading from a file with extended characters, you will need to specify the file encoding.

Note

To read a file a single line of text at a time, use the OpenTextFileReader method of the My.Computer.FileSystem object. The OpenTextFileReader method returns a StreamReader object. You can use the ReadLine method of the StreamReader object to read a file one line at a time. You can test for the end of the file using the EndOfStream method of the StreamReader object.

To read from a text file

Use the ReadAllText method of the My.Computer.FileSystem object to read the contents of a text file into a string, supplying the path. The following example reads the contents of test.txt into a string and then displays it in a message box.

Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt")
MsgBox(fileReader)

To read from a text file that is encoded

Use the ReadAllText method of the My.Computer.FileSystem object to read the contents of a text file into a string, supplying the path and file encoding type. The following example reads the contents of the UTF32 file test.txt into a string and then displays it in a message box.

Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt",
   System.Text.Encoding.UTF32)
MsgBox(fileReader)

Robust Programming

The following conditions may cause an exception:

  • The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path (ArgumentException).

  • The path is not valid because it is Nothing (ArgumentNullException).

  • The file does not exist (FileNotFoundException).

  • The file is in use by another process or an I/O error occurs (IOException).

  • The path exceeds the system-defined maximum length (PathTooLongException).

  • A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

  • There is not enough memory to write the string to buffer (OutOfMemoryException).

  • The user lacks necessary permissions to view the path (SecurityException).

Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a Visual Basic source file.

Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to read from the file may fail.

See also

  • FileSystem
  • ReadAllText
  • Reading from Files
  • How to: Read From Comma-Delimited Text Files
  • How to: Read From Fixed-width Text Files
  • How to: Read From Text Files with Multiple Formats
  • Troubleshooting: Reading from and Writing to Text Files
  • Walkthrough: Manipulating Files and Directories in Visual Basic
  • File Encodings

Feedback

Submit and view feedback for

Programs that calculate the total of a series of numbers typically use two elements:

1. A loop that reads each number in the series
2. A variable that accumulates the total of the numbers as they are read

The variable that is used to accumulate the total of the numbers is called an accumulator. It is often said that the loop keeps a running total because it accumulates the total as it reads each number in the series.

If the accumulator starts with any value other than 0, it will not contain the correct total when the loop finishes.

p. 315

A file containing data that has not been converted to text. As a consequence, you cannot view the contents of the binary file with a text editor.

To add an OpenFileDialog control to a form, double-click the OpenFileDialog tool under the Dialogs group in the Toolbox window. When the control is created, it does not appear on the form, but in an area at the bottom of the Designer known as the component tray.

The variable count is used as a counter variable, which means it is regularly incremented in each loop iteration. In essence, the count variable keeps count of the number of iterations the loop as performed. Counter variables are commonly used to control the number of times a loop iterates.

p. 274

Counter Variable in Loop Expression

Not only may the counter variable be initialized in the initialization expression, but it may also be declared there, for example:

for (int count = 1; count {
MessageBox.Show("Hello");
}

In this loop, the count variable is both declared and initialized in the initialization expression. If the variable is used only in the loop, it makes sense to define it in the loop header. This makes the variable's purpose clearer.

When declared in this way, the scope of the Variable is limited to the loop. This means you cannot access the Variable in statements outside the loop.

p. 287

Counter Variable Decrementing

Although it is generally incremented in a count-controlled loop, you can alternatively decrement it. For example:

for (int count = 10; count >= 0; count--)
{
MessageBox.Show(count.ToString( ));
}
MessageBox.Show("Blastoff!");

During the first iteration, count is 10, during the second iteration Count is 9, and so forth.

Counter Variable in for Loop

Because the four tests Boolean expression before it performs in iteration, it is a pretest loop. It is possible to write a for loop in such a way that it will never injury. Here is an example:

for (count = 6; count {
MessageBox.Show("Hello");
}

Because the variable count is initialized to a value that makes the Boolean expression false from the beginning, this loop terminates as soon as it begins.

p. 287

Counter Variable in Update Expression

In the update expression, the counter variable is typically incremented by 1. This makes it convenient to use the ++ operator in the increment expression. This is not a requirement, however. You can write virtually any expression you wish as the update expression. For example, the following loop increments count by 10:

for (int count = 0; count {
MessageBox.Show(count.ToString( ));
}

p. 287

To decrease the value of a variable. Operator: (--)

Also known as random access file. Allows you to jump directly to any piece of data in the file without reading the data that comes before it. Similar to how a CD or MP3 player works.

An object associated with a specific file and provides a way for the program to work with that file. In the program, a variable is linked with it. We say the variable is linked with the object. This variable is used to carry out any operations performed on the file. See figure 5-19.

p. 295

When the user selects a file with the Open dialog box, the file's path and file name are stored in the control's _____________. Assume openFile is the name of an OpenFileDialog control. The following code is an example of how you can display an Open dialog box and, if the user clicks the Open button to dismiss the dialog box, open the selected file:

StreamReader inputFile;

if (openFile.ShowDialog( ) == DialogResult.OK)
{
//Open the selected file.
inputFile =
File.OpenText(openFile.Filename);

//Continue processing the file...
}
else
{
MessageBox.Show("Operation canceled.");
}

p. 321

To increase the value of a variable num by 1.

nun = num + 1
operator: ++

InitialDirectory property

By default, the Open dialog box displays the contents of the user's Documents directory (or folder). You can specify another directory to be initially displayed by storing its path in the ______________. For example, the following code stores the path C:Data in the openFile control's InitialDirectory property before displaying an Open dialog box:

openFile.InitialDirectory = "C:\Data";

if (openFile.ShowDialog( ) == DialogResult.OK)
{
//Continue to process selected file...
}
else
{
//The operation was cancelled.
}

p. 322

initialization expression

It is normally used to initialize a counter variable to it's starting value. This is the first action performed by the loop, and it is only done once.

for (InitializationExpression; TestExpression; UpdateExpression) statement;

Used to describe a file from which data is read. The program gets input from the file.

To add an item to a ListBox control with code, you call the control's Items.Add method.

ListBoxName.Items.Add(Item);

ListBoxName is the name of the ListBox control. Item is the value to be added to the Items property.

p. 269

Erases all the items in the Items property. Here's the general format:

ListBoxName.Items.Clear( );

I.E., assume an application has a ListBox control named employeesListBox. The following statement clears all the items in the list:

employeesListBox.Items.Clear( );

Reports the number of items stored in the ListBox. If it is empty, the Items.Count property equals 0.

The Items.Count property holds an integer value. Assuming numEmployees is an int variable, the following statement assigns the number of items in the employeesListBox to the numEmployees variable:

numEmployees = employeesListBox.Items.Count;

Each time the loop executes its statement or statements we say it is performing an ____________.

When you run an application, the applications form is loaded into memory and an event known as the _____ _______ takes place.

Once you have created a random object, you can call it's ____ ______ to get a random integer number. The following code shows an example:

// Declare an int variable.
int number;

// Create a random object.
Random rand = new random( );

// Get a random integer and assign it to a number.
number = rand.Next( );

In code, you can display an Open dialog box by calling the OpenFileDialog control's ShowDialog method. For example, assume we have created an OpenFileDialog control and changed its name to openFile. The following statement calls the control's ShowDialog method:

openFile.ShowDialog( );

p. 320

Displays a standard Windows Open dialog box. It is useful in applications that must open an existing file because it allows the user to browse the system and select the file.

p. 320

Used to describe a file to which data is written. This program stores output in it.

When ++ and -- operators are written after their operands (or on the right side).

The do-while loop is a ________ ____. This means it performs an iteration before testing it's Boolean expression. As a result, the do-while loop always performs at least one iteration, even if it's Boolean expression is false to begin with.

When operators (++, --) are written before their operands. Examples:

++num;
--num;

The while loop is known as a _______ ____, which means test its condition before performing and iteration. Because the test is done at the beginning of the loop, you usually have to perform some steps prior to the loop to make sure the loop executes at least once. Notice the declaration of the count variable in the while Loop Demo program:

int count = 1;

p. 274

When you work with a direct access file (which is also known as a ______ ______ ____), you can jump directly to you in a piece of data in the file without reading the data that comes before it.

When a program works with an import file, a special value known as a _____ ________ is internally maintained for that file. A file's ____ ________ marks the location of the next item that will be read from the file. When an input file is open, it's ____ ________ is initially set to the first item in the file.

Read data from a text file, you create a StreamReader object. You can then use the StreamReader class's ________ ______ to read a line of text from the file.

p. 306

Programs that calculate the total of the series of numbers typically use two elements:

• A loop that reads each number in the series
• A variable that accumulates the total of the numbers as they are read.

The variable that is used to accumulate the total of the numbers is called an accumulation. It is often said that the loop keeps a _______ _____ because it accumulates the total as it reads each number in the series.

Allows the user to browse the system and select a location and name for a file that is about to be saved.

In code, you can display a ____ __ ______ ___ by calling the SaveFileDialog control's ShowDialog method.

To add a ______________ _______ to a form, double-click the ______________ tool in the Toolbox window. When the control is created, it appears in the component tray at the bottom of the Designer. The control will be given a default name such as _______________1, but you can change the name with the Name property.

The formula used to generate random numbers has to be initialized with a value known as a ____ _____. The ____ _____ is used in the calculation that returns the next random number in the series. When a Random object is created in memory, it retrieves the system time from the computer's internal clock and uses that as the ____ _____.

When you work with a __________ ______ ____, you access data from the beginning of the file to the end of the file.

Used to read data from a text file. Requires the following directive at the top of your program:

using System.IO;

Used to write data to a text file. Requires the following directive at the top of your programs:

using System.IO;

This is a Boolean expression that controls the execution of the loop. As long as this expression is true, the body of the for loop will repeat. The for loop is a pretest loop, so it evaluates the test expression before each iteration.

Contains data that has been encoded as text using a scheme such as Unicode. Even if the file contains numbers, those numbers are stored in the file as a series of characters. As a result, the file may be opened and viewed in a text editor such as notepad.

You can change the default text displayed in the title bar by changing the control's _____ ________.

Executes at the end of each iteration. Typically, this is a statement that increments the loop's counter variable.

p. 284, 287

while (BooleanExpression)
{
statement;
statement;
etc.
}

The set of statements is repeated while the Boolean expression is true.

We refer to the first line as the while clause. The while clause begins with the word while, followed by a Boolean expression that is enclosed in parentheses. Beginning on the next line is a set of statements enclosed on curly braces. The block of statements is known as the body of the loop.

Writes an item of data to a file and then writes a newline character. The newline character specifies the end of a line of text.

p. 297

Used to write a line of text to a file.

p. 296

When a piece of data is read from a file?

When a piece of data is read from a file, it is copied from the file into the program. Closing a file disconnects the communication between the file and the program. In Python, there is nothing that can be done if the program tries to access a file to read that does not exist.

What is the process of retrieving data from a file called?

Data recovery is the process of restoring data that has been lost, accidentally deleted, corrupted or made inaccessible. In enterprise IT, data recovery typically refers to the restoration of data to a desktop, laptop, server or external storage system from a backup.

When data is written to a file it is described as a?

What is an output file? a file that data is written to. It is called an output file because the program stores output in it.

When working with this type of file you can jump directly to any piece of data in the file without reading the data that comes before it?

When working with a sequential access file, you can jump directly to any piece of data in the file without reading the data that comes before it. 2. When an input file is opened, its read position is initially set to the first item in the file.