600
1200
1800
2400
3000
3600
4200
4800
5400
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")
Next
sw.Close()
End Sub
This is one of the simplest ways to create a
text file. If the file already exist it is overwritten.
Just:
-
Open the file using StreamWriter
-
Write text to the file with Write or Writeline
-
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
Do
sdx = sr.ReadLine()
Console.WriteLine(sdx)
Loop Until sr.EndOfStream
sr.Close()
End Sub
One of the simplest possible ways to read a text file
Just:
-
Open file with StreamReader.New(filename)
-
Loop through file with ReadLine
-
Save the string from ReadLine
-
Keep looping until StreamReader.EndOfStream
-
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
Next
File.WriteAllLines(path, buffer)
End Sub
This one is simple as well.
-
Create a string array to hold your data
-
Pass the file name and string array to File.WriteAllLines
-
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
-
Dim a string array to hold your data
-
call File.ReadAllLines to fill it
-
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)
Next
sw.Close()
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.