This question comes up all the time. The .NET framework provides easy to use classes for reading and writing to text files.

The Classes to use are the StreamReader and StreamWriter classes, which are found in the System.IO namespace. If you are going to be using lots of file access methods in your program, you can qualify the namespace by adding

VB Code:
  1. Imports System.IO

to your program, before any class definitions.

Otherwise, you can access the StreamReader and StreamWriter classes by qualifying them within your program. For example

VB Code:
  1. Dim SR As IO.StreamReader

Using them is fairly straightforward, but one key thing must be kept in mind. That is, that they are for sequential reading and writing. If you wish to open an existing file, and replace some line in the middle, you're going to have to do a little more work, or treat the text file as a Database and use ADO.NET to access it.

StreamReaders read line by line, and StreamWriters write Line by Line.

Here is a basic example of reading using a streamreader:

VB Code:
  1. Private Sub ReadFromTextFile()
  2.         Dim myReadFilePath As String = Application.StartupPath + "\MyTextFile.TXT"
  3.         'This is how to point to a file in the same directory as your program
  4.         'I almost always put my reader routines in an IF statement, so that I don't throw
  5.         'an exception.
  6.         If IO.File.Exists(myReadFilePath) Then
  7.             Dim sr As New IO.StreamReader(myReadFilePath) 'Any string value with a file path
  8.             'For this example, we will read the Text file into a RichTextBox
  9.             While Not (sr.Peek = -1)
  10.                 'The Peek method checks to see if there is more text coming
  11.                 'Without advancind the StreamReader, and returns -1 if the end of file is reached.
  12.                 'Alternatively, you could use a for loop, etc, if you wanted to read a specific
  13.                 'Number of lines.
  14.                 RichTextBox1.SelectedText = sr.ReadLine() + Environment.NewLine
  15.                 'The ReadLine Method advances the streamreader one line, and returns the value of
  16.                 'The string read from the file.
  17.                 'The Environment.NewLine simply adds a new line to the RichTextBox we are using
  18.             End While
  19.             sr.Close()
  20.         End If
  21.     End Sub

Now let's say you want to do multiple things with each line read in. It's important to note that each time StreamReader.ReadLine() is called, it returns a new line from the text file. So for instance, while the below code will compile, it will not give the anticipated result:
VB Code:
  1. Private Sub BuggyReadMethod()
  2.         Dim myReadFilePath As String = Application.StartupPath + "\MyTextFile.TXT"
  3.         If IO.File.Exists(myReadFilePath) Then
  4.             Dim sr As New IO.StreamReader(myReadFilePath) 'Any string value with a file path
  5.             Dim strArray(10) As String
  6.             While Not (sr.Peek = -1)
  7.                 Dim s As String = sr.ReadLine().Replace("info", "Information")
  8.                 strArray = sr.ReadLine().Split(" "c) 'Put each word into the string array
  9.             End While
  10.             'While that will compile just fine, the ReadLine Method is called twice - so
  11.             'It will advance the StreamReader two times, giving different strings each time.
  12.         End If
  13.     End Sub

So, if within your read loop, you wish to do more than one thing with the read in line, you must put it in a string variable first, like this:

VB Code:
  1. Private Sub BetterReadMethod()
  2.         Dim myReadFilePath As String = Application.StartupPath + "\MyTextFile.TXT"
  3.         If IO.File.Exists(myReadFilePath) Then
  4.             Dim sr As New IO.StreamReader(myReadFilePath)
  5.             Dim strArray(10) As String
  6.             While Not (sr.Peek = -1)
  7.                 Dim Line As String
  8.                 Line = sr.ReadLine()
  9.                 Line = Line.Replace("info", "Information")
  10.                 strArray = Line.Split(" "c) 'Put each word into the string array
  11.             End While
  12.         End If
  13.     End Sub

The StreamReader class also exposes a ReadToEnd method, which will return the entire value of the textfile from whatever point in it the streamreader is at. This can be used for optimizing read speed, and when you have a variable that can accept a large string with newLine characters in it (such as a richtextbox)

VB Code:
  1. Private Sub ReadToEndExample()
  2.         Dim myReadFilePath As String = Application.StartupPath + "\MyTextFile.TXT"
  3.         If IO.File.Exists(myReadFilePath) Then
  4.             Dim sr As New IO.StreamReader(myReadFilePath)
  5.             'You could optionally read in some header data, or whatever before calling readtoEnd
  6.             Dim headerstring As String = sr.ReadLine()
  7.             RichTextBox1.SelectedText = sr.ReadToEnd 'This wil return all data from the second line until the end of file.
  8.             sr.Close()
  9.         End If
  10.     End Sub

That's pretty much it for the StreamReader, for basic uses.

The StreamWriter works almost exactly the same. The following example opens up a new file, and writes a few lines of text in it. Note the difference between Write and WriteLine is only that a newline character is written with the WriteLine method.


VB Code:
  1. Private Sub WriteTextFile()
  2.         Dim myWritePath As String = Application.StartupPath + "\myoutputFile.txt"
  3.         Dim sw As New IO.StreamWriter(myWritePath)
  4.         'Now, we just start writing stuff.
  5.         sw.WriteLine("This is some info to put in a text file.")
  6.         'The Write method will not put a new line character, like this:
  7.         sw.Write("This is")
  8.         sw.WriteLine(" some other info, using a write statement")
  9.         sw.Close() 'If this is not placed, the file will not save, and you will have an empty file.
  10.     End Sub

Make sure you call StreamWriter.Close(), otherwise your efforts will be wasted on an empty file! The above program outputs a file with this inside of it:
Code:
This is some info to put in a text file.
This is some other info, using a write statement
Notice the second line is compounded because of the use of Write instead of WriteLine.

Sometimes you may wish to only add to a file, such as in the case of a log file, or a history file, etc.. The method for this is also fairly easy, and involves only adding one additional variable to the constructor of the StreamWriter, as in the below example.

VB Code:
  1. Private Sub WriteAppendedText()
  2.         Dim myWritePath As String = Application.StartupPath + "\myLogFile.Log"
  3.         'Here is a method for writing a log file, using the append mode of the
  4.         Dim sw As New IO.StreamWriter(myWritePath, True)
  5.         'The second parameter (True) in this overloaded constructor is a boolean value
  6.         'That tells the streamwriter to Append if the file exists.
  7.         'Note that if it doesn't exist, it will simply start a new file.
  8.         'Calling the IO.File.Exists method may be appropriate if you need to be appending
  9.         'an existing file
  10.         sw.WriteLine(DateTime.Now.ToShortTimeString + " " + DateTime.Now.ToShortDateString + ": Appended the log file.")
  11.         'The above line simply adds the time and date, and a short message to an existing file.
  12.     End Sub

So, that's it for sequential reading and writing. Now quite often, as mentioned in the introduction, you might want to open a file, scan for something, and replace it. You can do this with the StreamReader and StreamWriter, but note that neither can do the full job, and you will need both. The following example uses a temporary file, and overwrites the original with the temporary file after it is finished using the IO.File.Copy method.

VB Code:
  1. Private Sub FindAndReplace()
  2.         Dim MyTempFile As String = "tempfile.txt"
  3.         Dim MyFile As String = Application.StartupPath + "\Appdata.txt"
  4.         If IO.File.Exists(MyFile) Then
  5.             Dim sr As New IO.StreamReader(MyFile)
  6.             Dim sw As New IO.StreamWriter(MyTempFile)
  7.             'The below example replaces all instances of the word Bill with William.
  8.             While Not (sr.Peek = -1)
  9.                 Dim Line As String = sr.ReadLine 'read into a string
  10.                 Line = Line.Replace("Bill", "William") 'Do the work with the string
  11.                 sw.WriteLine(Line) 'Write the new line
  12.             End While
  13.             sr.Close()
  14.             sw.Close()
  15.             'Occasionally, the StreamReader destructor doesn't let go of the file quick enough
  16.             'to use it again.  To remedy this, you can use the GC.Collect() Method to force the
  17.             'Program to clean up resources
  18.             GC.Collect()
  19.             IO.File.Copy(MyTempFile, MyFile, True) 'True specifies to overwrite.
  20.         End If
  21.     End Sub

That's it! If someone would like to add in how to do it via ADO.NET, that might be nice to have too.

Additional information on the StreamReader class can be found on MSDN here and additonal info on the StreamWriter class can be found here

Bill