Read Text From/Write Text To a File

Upload your Visual Basic Code that you want to share with everyone. Visual Studio 2012 and UP
User avatar

Topic author
Edward572
Site Admin
Site Admin
Posts: 67
Joined: Sat Dec 29, 2012 6:13 pm
Location: Ontario, Canada
Canada

Read Text From/Write Text To a File

Post by Edward572 » Thu May 05, 2016 1:11 am

Read Text From/Write Text To a File (VB.NET)
Category:
C#, VB.NET, ASP.NET
Type:
Snippets
Difficulty:
Beginning
Author:
Intelligent Solutions Inc.

Version Compatibility: Visual Basic.NET, ASP.NET
More information:
These function allows you to retrieve a text file's contents and write text to a file in VB.NET. They also optionally provide error information if they fail. Sample Usage:

Code: Select all

sContents = GetFileContents("C:\test.txt", sErr)
        If sErr = "" Then
            Debug.WriteLine("File Contents: " & sContents)
            'Save to different file
            bAns = SaveTextToFile(sContents, "D:\Test.txt", sErr)
            If bAns Then
                Debug.WriteLine("File Saved!")
            Else
                Debug.WriteLine("Error Saving File: " & sErr)
            End If

        Else
            Debug.WriteLine("Error retrieving file: " & sErr)
        End If


Code: Select all

Public Function GetFileContents(ByVal FullPath As String, _
       Optional ByRef ErrInfo As String = "") As String

        Dim strContents As String
        Dim objReader As StreamReader
        Try

            objReader = New StreamReader(FullPath)
            strContents = objReader.ReadToEnd()
            objReader.Close()
            Return strContents
        Catch Ex As Exception
            ErrInfo = Ex.Message
        End Try
    End Function

    Public Function SaveTextToFile(ByVal strData As String, _
     ByVal FullPath As String, _
       Optional ByVal ErrInfo As String = "") As Boolean

        Dim Contents As String
        Dim bAns As Boolean = False
        Dim objReader As StreamWriter
        Try

       
            objReader = New StreamWriter(FullPath)
            objReader.Write(strData)
            objReader.Close()
            bAns = True
        Catch Ex As Exception
            ErrInfo = Ex.Message

        End Try
        Return bAns
    End Function


Instructions: Copy the declarations and code below and paste directly into your VB project.
Cheers All, Have A Good One
StormerSoft.Com

Bacon is the greatest food
Forum StormerSoft.Com