File.OpenRead Method In VB.NET

This article explains about Open read method in VB.NET
  • 3830

File.OpenRead Method

The OpenRead method opens a file for reading. The method returns a FileStream object that is used to read a file using its Read method.

Dim fileName As String = "C:\Temp\MaheshTXFITx.txt"

Dim fi As New IO.FileInfo(fileName)

Dim fs As FileStream = fi.OpenRead()

The file is read into a byte array. The following code snippet uses the FileStream.Read method and gets text into a byte array and then it is converted to a string using UTF8Encoding.GetString method.

Using fs As FileStream = fi.OpenRead()

            Dim byteArray As Byte() = New Byte(1023) {}

            Dim fileContent As New UTF8Encoding(True)

            While fs.Read(byteArray, 0, byteArray.Length) > 0

                Console.WriteLine(fileContent.GetString(byteArray))

            End While

End Using

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 fs As FileStream = fi.OpenRead()

                Dim byteArray As Byte() = New Byte(1023) {}

                Dim fileContent As New UTF8Encoding(True)

                While fs.Read(byteArray, 0, byteArray.Length) > 0

                    Console.WriteLine(fileContent.GetString(byteArray))

                End While

                Console.ReadLine()

            End Using

        Catch Ex As Exception

            Console.WriteLine(Ex.ToString())

        End Try

    End Sub

End Module



Categories

More Articles

© 2013 dotNetheaven. All rights reserved.