|
|
Title | Open text file by using CreateText, AppendText, and OpenText in Visual Basic .NET |
Description | This example shows how to open text file by using CreateText, AppendText, and OpenText in Visual Basic .NET |
Keywords | CreateText, AppendText, OpenText, Exists, open file, read file, StreamWriter, StreamReader, VB.NET |
Categories | Files and Directories, VB.NET |
|
|
Programs can use the StreamReader and StreamWriter classes to read and write text files in Visual Basic .NET. These methods make opening files easier.
When you click the Create File button, the program uses the CreateText function to open a file, overwriting the previous file if it exists. It writes text from the text box into the file and closes it.
When you click the Append File button, the program uses the AppendText function to open a file for appending to the end. If the file doesn't exist, AppendText creates it. The program writes text into the file and closes it.
When you click the Show File button, the program uses the Exists function to see if the file exists. If the file does exist, the program uses the OpenText function to open the file for reading. The program writes text into the file and closes it.
|
|
' Overwrite the file.
Private Sub btnCreateFile_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
btnCreateFile.Click
Dim stream_writer As StreamWriter
stream_writer = CreateText(txtFileName.Text)
stream_writer.WriteLine(txtText.Text)
stream_writer.Close()
End Sub
' Append to the end of the file.
Private Sub btnAppendFile_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
btnAppendFile.Click
Dim stream_writer As StreamWriter
stream_writer = AppendText(txtFileName.Text)
stream_writer.WriteLine(txtText.Text)
stream_writer.Close()
End Sub
Private Sub btnShowFile_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
btnShowFile.Click
Dim stream_reader As StreamReader
stream_reader = OpenText(txtFileName.Text)
txtFile.Text = stream_reader.ReadToEnd
txtFile.Select(0, 0)
stream_reader.Close()
End Sub
|
|
|
|
|
|