- This topic explains about how to read text file and write text file in VB programming.
- This is done with the help of stream reader and stream writer.
- Tools needed: TextBox1 (TextBox1), Button1 (Button1), Button2 (Button2)
System.IO Namespace – Read text file and write text file in VB
- The System.IO namespace contains types that allow read text file and write text file and data streams and types that provide basic file and directory support.
StreamReader Class – Read text file and write text file in VB
- Implements a TextReader that reads characters from a byte stream in a particular encoding.
- Syntax for StreamReader Class
|
1 2 3 4 5 |
'Declaration <SerializableAttribute> _ <ComVisibleAttribute(True)> _ Public Class StreamReader _ Inherits TextReader |
StreamWriter Class – Read text file and write text file in VB
- Implement a TextWriter for writing characters to a stream in a particular encoding.
- Syntax for StreamWriter Class
|
1 2 3 4 5 |
'Declaration <SerializableAttribute> _ <ComVisibleAttribute(True)> _ Public Class StreamWriter _ Inherits TextWriter |
StreamReader.ReadToEnd Method – Read text file and write text file in VB
- Help to reads all characters from the current position to the end of the stream.
Read text file and write text file in VB – Complete Code
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try Dim file_name As String = "C:/text.txt" ' Application.StartupPath() & "/text.dat" Dim stream_reader As New IO.StreamReader(file_name) Try TextBox1.Text = stream_reader.ReadToEnd() TextBox1.Select(0, 0) Finally stream_reader.Close() End Try Catch exc As System.IO.FileNotFoundException ' Ignore this error. Catch exc As Exception ' Report other errors. MsgBox(exc.Message, MsgBoxStyle.Exclamation, "Read " & _ "Error") End Try End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Try Dim file_name As String = "C:/text.txt" 'Application.StartupPath() & "/text.dat" Dim stream_writer As New IO.StreamWriter(file_name, _ False) Try stream_writer.Write(TextBox1.Text) Finally stream_writer.Close() End Try Catch exc As Exception ' Report all errors. MsgBox(exc.Message, MsgBoxStyle.Exclamation, "Read " & _ "Error") End Try End Sub |
Read text file and write text file in VB
If you have any suggestions or doubts, please inform us…







