Reading Text Files in Visual C# .NET

Skip Navigation LinksIrocon > Blog > 2003 > November, 2003 > November 15, 2003 > Reading Text Files in Visual C# .NET

Reading Text Files in Visual C# .NET

To load and read a text file from Visual Basic .NET, follow these steps:

1. Open Visual Studio .NET. Create a new Console Application in Visual Basic .NET. Visual Studio creates a Module for you, along with an empty Main() procedure.

2. Make sure that the project references at least the System namespace. Use the Imports statement on the System, System.IO, and System.Collections namespaces so you are not required to qualify declarations from these namespaces later in your code. You must use these statements prior to any other declarations.Imports System
Imports System.IO
Imports System.Collections

3. To open a file for reading, create a new instance of a StreamReader object, and pass the file's path into the constructor as follows:Dim objReader As New StreamReader("c:\test.txt")

4. You will need a string variable in which to store each line of the file as you process. Because you will be adding these lines to an ArrayList, declare and create an object of that type as well.Dim sLine As String = ""
Dim arrText As New ArrayList()

5. There are several ways to read the file in, including the ReadToEnd method which reads in the entire file at once. However, for this example, you can use the ReadLine method to bring in the file one line at a time. When the end of the file is reached, this method returns "Nothing," which allows a way to end your loop. As you read each line from the file, you can use the Add method of the ArrayList to insert the lines into your ArrayList class.Do
sLine = objReader.ReadLine()
If Not sLine Is Nothing Then
arrText.Add(sLine)
End If
Loop Until sLine Is Nothing
objReader.Close()

6. Use a "For Each" loop to write the contents of your newly filled ArrayList to the console as follows:For Each sLine In arrText
Console.WriteLine(sLine)
Next
Console.ReadLine()

7. Save and run your code, which produces a listing of your file to the console.
------------------------

This information was obtained from the Microsoft Knowledge Base Article - 302309

Last Updated:Thursday, September 02, 2010By:alferoSource#

Would you like to comment?

Sign in with your OpenID. If you do not know what OpenID is, find out.