In this article we will learn various text file operations such as opening, creating, reading, writing, copying and deleting a file and how to determine whether a file exists or not.
Dim TempFile As System.IO.File
Dim TempRead As System.IO.StreamReader
Dim TempWrite As System.IO.StreamWriter
Info about file existence
If File.Exists("C:\TempText.txt") Then
MessageBox.Show("File found")
Else
MessageBox.Show("File not found")
End If
Create file
TempWrite = File.CreateText("C:\TempText.txt")
Open file
TempRead = File.OpenText("C:\TempText.txt")
Read file
You can also read an entire text file from the current position to the end of the file by using the ReadToEnd method, as shown in the following code :
Dim FullFileStr As String
TempRead = File.OpenText("C:\TempText.txt")
FullFileStr = TempRead.ReadToEnd()
Write file
TempWrite.WriteLine("Hello")
Copy file
Dim fileDestinationStr As String = "D:\TempText.txt"
If File.Exists("C:\TempText.txt") Then
File.Copy("C:\TempText.txt", fileDestinationStr)
End If
Delete file
If File.Exists("C:\TempText.txt") Then
File.Delete("C:\TempText.txt")
Else
MessageBox.Show("File not found")
End If