Input and Output
  Read a text file
  List a directory
  Create a log file
  Read and write large files
  Read and write binary data
  Watch file system changes

Get URL for this page

How Do I...Read a text file?

This sample retrieves information from a text file, and uses an ArrayList to display that information for the user.

Opening and reading files for read access is an important part of IO functionality, even if you do not need to write to the file in question. In this example, we open a file for reading. This is useful for reading text files, but inappropriate for binary files. In this example, we use one of many methods available for opening the file. Although many data structures are available for storing information retrieved from the file, an ArrayList is the easiest to use. A more detailed analysis of the code follows the example.

 
VB Anagrams.aspx

[Run Sample] | [View Source]

To open a file, you need to manipulate a number of objects found in the IO namespace. The first class of interest is the File class, which defines the general methods and rules for dealing with files. The File class has a number of different methods for opening files, but for this specific scenario, the most appropriate is OpenText. This is because this particular method returns a StreamReader object, which is ideal for reading lines of information from a standard text file. The following code demonstrates using the OpenText method, passing it the name of the file you intend to open. You can include a fully-qualified path when specifying the file.


Dim din As StreamReader = File.OpenText ("words.txt")
VB

Here are some other ways in which you can open files. Each of these alternative samples could replace the previous sample, although with this code, you have to do a bit more work to translate the return value back to a StreamReader object. This is because each of these methods returns a Stream object, which can be used to construct a new instance of StreamReader. While you can use a Stream to read information from a file, a StreamReader lessens your workload by providing you with a richer set of methods that you can use to get information from the file that you have opened.


'  Use OpenRead which opens a file in read-only mode
Dim din As StreamReader = New StreamReader( File.OpenRead("words.txt") )

'  Use Open, which accepts the FileMode to open the file in.
'  Here we request FileMode.Open, but an alternative would have been Create, or OpenOrCreate
Dim din As StreamReader = New StreamReader( File.Open("words.txt", FileMode.Open) )
VB

Once you have opened your file, you will need to get the information from it. As mentioned earlier, the StreamReader is good for this because it provides you with the ReadLine method which enables you to get one line at a time. Of course, you need to know how the information in your file is stored to interpret it correctly. In this sample, the input file consists of one-word lines of information, making it easier to interpret.

You can place the information you retrieve into a number of datastores. In this example, you could just place each line in a string, but that is not typically what would happen. An array is a possible solution, but there is no way to tell in advance how many lines it is going to read. It would have to keep resizing, or remaking, the array (which would require extra work). The ideal solution in this scenario is to choose an ArrayList, a collection on which we can simply use the Add method to add more elements. This saves a lot of effort.

The following sample reads each new line from our opened file and places each new piece of information into an ArrayList. You can detect the end of the file by checking to see if the last thing that was read was null. If it was, then it has reached the end of the file (note that an empty line will not equal null).


Dim str As String
Dim al As ArrayList = New ArrayList() ' make our temporary storage object

' loop through all the rows, stopping when we reach the end of file
Do
	str = din.ReadLine()

	If str <> Nothing Then
		al.Add(str)           ' add each element to our ArrayList
	End If
Loop Until str = Nothing
VB

Now that you have all your information from the file, you can manipulate it at will. In this example, you can choose to simply print out the information for the user. To do this, you can use a for each statement to go through all the elements in the ArrayList, printing each item to the Console object.


Dim s As String

For Each s in al
	Console.WriteLine (s)
Next s
VB

Summary

You can read information from a text file in a number of ways. One of the easiest is to use the File object's OpenText method, in combination with a StreamReader object to to retrieve one line of information at a time. It is recommended that you store the information you are retrieving in a temporary store such as an array, or an ArrayList.


Copyright 2001-2002 Microsoft Corporation. All rights reserved.