Monday, May 18, 2009

Easy File Reading and Writing

I recommend putting these in a module or class for repeated use.

Declarations
Imports System.IO
Code
'http://www.freevbcode.com/ShowCode.Asp?ID=4492
Public Function ReadFile(ByVal sFullPath As String, _
Optional ByRef sErrInfo As String = "") As String

Dim sContents As String
Dim oReader As StreamReader

Try
oReader = New StreamReader(sFullPath)
sContents = oReader.ReadToEnd()
oReader.Close()
Return sContents
Catch Ex As Exception
sErrInfo = Ex.Message
End Try

End Function

'http://www.freevbcode.com/ShowCode.Asp?ID=4492
Public Function WriteFile( _
ByVal sFullPath As String, ByVal sContents As String, _
Optional ByRef sErrInfo As String = "") As Boolean

Dim oReader As StreamWriter

Try
oReader = New StreamWriter(sFullPath)
oReader.Write(sContents)
oReader.Close()
Return True
Catch Ex As Exception
sErrInfo = Ex.Message
Return False
End Try

End Function

No comments:

Post a Comment