Read Write File using File Stream in Dot Net

file-computer

Read file in byte array in vb.net :

Public Function Reader(ByVal FilePath_ As String) As Byte()
        Dim BytArr(FileSystem.FileLen(FilePath_) - 1) As Byte
        Using fs As New FileStream(FilePath_, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
            fs.Read(BytArr, 0, BytArr.Length)
            fs.Close()
        End Using
        Return BytArr
End Function

Read file in String :

Public Function ReaderString(ByVal FilePath_ As String) As String
        Dim data_str As String
        Using fs As New FileStream(FilePath_, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
            Using Sr As New StreamReader(fs)
                data_str = Sr.ReadToEnd
                Sr.Close()
                fs.Close()
            End Using
            Return data_str
        End Using
End Function

Read File with Encoding (using default encoding as UTF8 ) :

 Public Function ReaderSUtf(ByVal Fpth As String, Optional encodng As System.Text.Encoding = Nothing) As String
        Dim data_str As String
        If encodng Is Nothing Then
            encodng = System.Text.Encoding.UTF8
        End If
        Using fs As New FileStream(Fpth, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
            Using Sr As New StreamReader(fs, encodng)
                data_str = Sr.ReadToEnd
                Sr.Close()
                fs.Close()
            End Using
            Return data_str
        End Using
 End Function

 

Leave a Comment