Read and Write files
The following example writes a line of text to a file.
'Write text to a file
Sub WriteTextToFile ()
Dim file As New System. IO. StreamWriter ("c: test.txt ")
File. WriteLine ("Here is the first line .")
File. Close ()
End Sub
In the following example, the text in the file is read to a string variable and then written to the console.
Sub ReadTextFromFile ()
Dim file As New System. IO. StreamReader ("c: test.txt ")
Dim words As String = file. ReadToEnd ()
Console. WriteLine (words)
File. Close ()
End Sub
The following example adds text to an existing file.
Sub AppendTextToFile ()
Dim file As New System. IO. StreamWriter ("c: test.txt", True)
File. WriteLine ("Here is another line .")
File. Close ()
End Sub
The following example reads a line from the file at a time and prints the text of each line to the console.
Sub ReadTextLinesFromFile ()
Dim file As New System. IO. StreamReader ("c: test.txt ")
Dim oneLine As String
OneLine = file. ReadLine ()
While (oneLine <> "")
Console. WriteLine (oneLine)
OneLine = file. ReadLine ()
End While
File. Close ()
End Sub
File Encoding
By default, both the StreamReader and StreamWriter classes use UTF-8 encoding. UTF-8 encoding correctly handles Unicode characters and ensures consistency between localized versions of the operating system.
You can use StreamReader to automatically detect the file encoding or specify the file encoding as a parameter in the constructor.
StreamWriter uses an encoding parameter on its constructor. If encoding is specified, Visual Basic writes a file to indicate the encoding used.