Results 1 to 3 of 3

Thread: Get text from a .txt file and Save to a String

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Mar 2005
    Posts
    546

    Get text from a .txt file and Save to a String

    How can I get all the lines of text from a .txt file and save them to a string variable? Also, If I put this string variable into a different .txt file later on, will the words still be formatted correctly on their proper lines etc.?
    Did you find a post in this thread useful? Please click Rate This Post.

  2. #2
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649

    Re: Get text from a .txt file and Save to a String

    VB Code:
    1. Public Function ReadFile(ByVal sFileName As String) As String
    2.     Dim hFile As Integer
    3.     On Error Resume Next
    4.     'Get a free file handle
    5.     hFile = FreeFile
    6.     'Open the file
    7.     Open sFileName For Input As #hFile
    8.         'read the whole content and return it
    9.         ReadFile = Input(LOF(hFile), hFile)
    10.         'Close the file
    11.     Close #hFile
    12. End Function
    You can use the above function like this:
    VB Code:
    1. Dim sText As String
    2. sText = ReadFile("c:\thePath\theFile.txt")
    Yes, if you save this text string (without changing it) you have made a copy of the origional file.
    VB Code:
    1. Public Sub SaveFile(ByVal sFileName As String, ByVal sText As String)
    2.     Dim hFile As Integer
    3.     On Error Resume Next
    4.     hFile = FreeFile
    5.     Open sFileName For Output As #hFile
    6.         Print #hFile, sText;
    7.     Close #hFile
    8. End Sub
    Here's an example:
    VB Code:
    1. Dim sTxt As String
    2. 'read the content of one (existing) file
    3. sTxt = ReadFile("c:\FirstFile.txt")
    4. 'save this to another file
    5. Call SaveFile("c:\SecondFile.txt", sTxt)

  3. #3
    PowerPoster RhinoBull's Avatar
    Join Date
    Mar 2004
    Location
    New Amsterdam
    Posts
    24,132

    Re: Get text from a .txt file and Save to a String

    Here ksi a quick sample for you:
    VB Code:
    1. Private Sub Command1_Click()
    2. Dim strText$, i%
    3. Dim arLines() As String
    4.  
    5.     Open "c:\temp\test.txt" For Input As #1
    6.         'read entire file into string variable
    7.         strText = Input(LOF(1), #1)
    8.         'split text on each carriage return
    9.         arLines = Split(strText, vbNewLine)
    10.         'read each line
    11.         For i = 0 To UBound(arLines)
    12.             Debug.Print arLines(i)
    13.         Next i
    14.     Close #1
    15.  
    16. End Sub

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width