File.OpenText Method In VB.NET
This article explains how to open an existing UTF-8 encoded text file for reading.
File.OpenText Method
The OpenText method opens an existing UTF-8 encoded text file for reading. The OpenText method takes a file name as a parameter and returns a StreamReader object.
Dim reader As StreamReader = fi.OpenText()
Once we have a StreamReader object, we can use its Read or ReadLine methods to read the contents. The ReadLine method reads one line at a time. The following code snippet loops through the entire content of a SteamReader and reads and prints one line at a time.
While (InlineAssignHelper(s, reader.ReadLine())) IsNot Nothing
Console.WriteLine(s)
End While
The following lists the complete code sample.
Imports System.Text
Imports System.IO
Module Module1
Sub Main()
Dim fileName As String = "C:\Temp\MaheshTXFITx.txt"
Dim fi As New IO.FileInfo(fileName)
' If file does not exist, create file
If Not fi.Exists Then
'Create the file.
Using fs As FileStream = fi.Create()
Dim info As [Byte]() = New UTF8Encoding(True).GetBytes("File Start")
fs.Write(info, 0, info.Length)
End Using
End If
Try
Using reader As StreamReader = fi.OpenText()
Dim s As String = ""
While (InlineAssignHelper(s, reader.ReadLine())) IsNot Nothing
Console.WriteLine(s)
End While
End Using
Catch Ex As Exception
Console.WriteLine(Ex.ToString())
End Try
End Sub
Private Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
target = value
Return value
End Function
End Module