Using File.IO.StreamWriter to create a text file
   Private Sub WriteText1(ByVal fn As String)
        Dim sw As New StreamWriter(fn)
        For xx = 1 To 5
            sw.WriteLine("This is a line of text")
    End Sub
This is one of the simplest ways to create a text file. If the file already exist it is overwritten.

  1. Open the file using StreamWriter
  2. Write text to the file with Write or Writeline
  3. Close the file
Using System.IO.StreamReader to read a text file
  Private Sub ReadText1(ByVal fn As String)
        Dim sr As New StreamReader(fn)
        Dim sdx As String
            sdx = sr.ReadLine()
        Loop Until sr.EndOfStream
    End Sub
One of the simplest possible ways to read a text file
  1. Open file with StreamReader.New(filename)
  2. Loop through file with ReadLine
  3. Save the string from ReadLine
  4. Keep looping until StreamReader.EndOfStream
  5. Close the file
Using File.WriteAllLines(path string, string())
 Private Sub WriteText2(ByVal path As String)
        Dim buffer(5) As String
        For xx = 0 To 4
            buffer(xx) = "This is a test " + xx.ToString
        File.WriteAllLines(path, buffer)
 End Sub
This one is simple as well.
  1. Create a string array to hold your data
  2. Pass the file name and string array to File.WriteAllLines
  3. File.WriteAllLines closes the file for you
Using File.ReadAllLines(path string)
  Private Sub ReadText2(ByVal path As String)
        Dim buffer() As String
        buffer = File.ReadAllLines(path)
    End Sub
  1. Dim a string array to hold your data
  2. call File.ReadAllLines to fill it
  3. File.ReadAllLines closes the file for you
Using File.WriteAllText(path string, string array)
 Private Sub WriteText3(ByVal path As String)
        Dim buffer As String
        buffer = "this is a test"
        File.WriteAllText(path, buffer)
    End Sub
Simply writes the text string passed in to a text file whose name is defined in the path statement.
Using string = File.ReadAllText(path string)
Private Sub ReadText3(ByVal path As String)
        Dim buffer As String
        buffer = File.ReadAllText(path)
    End Sub
File.ReadAllText does not return an array of strings, but puts the whole text file in the one string. If the file had been saved as individual lines, this routine will return one long string with all lines appended together
Using File.IO.StreamWriter to append text to a file
 Private Sub WriteText1Append(ByVal path As String,append as boolean)
        Dim sw As New StreamWriter(path, append) ' assume append = True
        For xx = 1 To 5
            sw.WriteLine("This is a line of text " + xx.ToString)
    End Sub
The second parameter controls whether to append to the file or not. If the second parameter is false then it is equivelent to WriteText1(path) in the first example.
Alone in a sea of non-programmers
Home Random Regular expressions Create control at runtime Text files: Read & Write