Reading and writing files
The following example writes one 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's The" ")"
File. Close ()
End Sub
The following example reads the text in a file into a string variable and then writes the text 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's another line.")
File. Close ()
End Sub
The following example reads one row from a file at a time, and then prints each line of text 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, the StreamReader and StreamWriter classes all 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 encoding of a file, or to specify the encoding of a file as a parameter on a constructor.
StreamWriter takes an encoding parameter on its constructor. If the encoding is specified, Visual Basic writes to the file to indicate the encoding being used.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.