Reading/Writing/Appending a Text File, Using VB.Net
.vb Code
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Windows.Forms
Imports System.IO
Public Class Form1
Private Sub file_write()
Dim path As String = "C:\ash"
' Parent Directory
Dim name As String = richTextBox1.Text
Dim ext As String = ".txt"
Dim fname As String = path & name & ext
Dim file1 As New FileInfo(fname)
Dim sw As StreamWriter = file1.CreateText()
sw.WriteLine("This is a demo for writing to a text file")
'Writing a string directly to the file
sw.WriteLine(richTextBox1.Text)
' Writing content read from the textbox in the form
sw.Close()
End Sub
Private Sub file_read()
Dim path As String = "C:\"
' Parent Directory
Dim name As String = richTextBox1.Text
Dim ext As String = ".txt"
Dim fname As String = path & name & ext
Dim readcontent As String
Dim file1 As New FileInfo(fname)
Dim sr As New StreamReader(fname)
readcontent = sr.ReadToEnd()
' Reading content from the file and storing to a string
sr.Close()
richTextBox1.Text = readcontent
' Display contents in a textbox in the form
End Sub
Private Sub file_append()
Dim path As String = "C:\"
' Parent Directory
Dim name As String = richTextBox1.Text
Dim ext As String = ".txt"
Dim fname As String = path & name & ext
' FileInfo file1 = new FileInfo(fname);
Dim sw As StreamWriter = File.AppendText(fname)
sw.WriteLine("This is a demo for appending text content to a file")
' Writing a string directly to the file
sw.WriteLine(richTextBox1.Text)
sw.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
file_read()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button2.Click
file_append()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button3.Click
file_write()
End Sub
End Class