Vb.net file read and write code

Source: Internet
Author: User

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.

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.