Classic VB - How can I read/write a text file?-VBForums
Results 1 to 1 of 1

Thread: Classic VB - How can I read/write a text file?

  1. #1

    Thread Starter
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Candon City, Ilocos Sur, Phils.
    Posts
    10,818

    Classic VB - How can I read/write a text file?

    You can read from (or write to) a text file using the Open statement, Close statement and various other statements for actually reading/writing.

    The Open statement has clauses for what type of access you want to the file, so you can specify if you want to read it as text, write to it as binary, and so on. You can also set locking options, to stop other programs from opening the file. For more details, go to the Index of VB help and see "Open statement".

    For all of these file access functions you need to specify a file number, which most people use 1 for. You should always use a number which is not already in use (as using the same will cause an error), luckily the next free number can be found using the FreeFile function as in the example below.

    An example of reading a file:
    VB Code:
    1. Dim sFileText as String
    2. Dim iFileNo as Integer
    3.   iFileNo = FreeFile
    4.       'open the file for reading
    5.   Open "C:\Test.txt" For Input As #iFileNo
    6. 'change this filename to an existing file!  (or run the example below first)
    7.  
    8.       'read the file until we reach the end
    9.   Do While Not EOF(iFileNo)
    10.     Input #iFileNo, sFileText
    11.       'show the text (you will probably want to replace this line as appropriate to your program!)
    12.     MsgBox sFileText
    13.   Loop
    14.  
    15.       'close the file (if you dont do this, you wont be able to open it again!)
    16.   Close #iFileNo
    (note: an alternative to Input # is Line Input # , which reads whole lines).


    An example of writing a file:
    VB Code:
    1. Dim sFileText as String
    2. Dim iFileNo as Integer
    3.   iFileNo = FreeFile
    4.       'open the file for writing
    5.   Open "C:\Test.txt" For Output As #iFileNo
    6. 'please note, if this file already exists it will be overwritten!
    7.  
    8.       'write some example text to the file
    9.   Print #iFileNo, "first line of text"
    10.   Print #iFileNo, "   second line of text"
    11.   Print #iFileNo, ""  'blank line
    12.   Print #iFileNo, "some more text!"
    13.  
    14.       'close the file (if you dont do this, you wont be able to open it again!)
    15.   Close #iFileNo
    (note: an alternative to Print # is Write # , which adds commas between items, and also puts the " character around strings).



    You can read files in a much faster way too, by simply loading the entire file at once. To do this you need to use binary mode, like so:
    VB Code:
    1. Function FileText(ByVal filename As String) As String
    2.     Dim handle As Integer
    3.      
    4.        ' ensure that the file exists
    5.     If Len(Dir$(filename)) = 0 Then
    6.         Err.Raise 53  ' File not found
    7.     End If
    8.      
    9.        ' open in binary mode
    10.     handle = FreeFile
    11.     Open filename$ For Binary As #handle
    12.        ' read the string and close the file
    13.     FileText = Space$(LOF(handle))
    14.     Get #handle, , FileText
    15.     Close #handle
    16. End Function


    Reading/writing files can also be acheived using FSO (FileSystemObject) as shown below. Please note that using FSO requires an extra reference (under "Project"->"References"), and therefore extra files to be installed with your application.
    VB Code:
    1. Option Explicit
    2. 'Set a reference to "Microsoft Scripting Runtime"
    3. Private Sub Command1_Click()
    4.        'declare and initiate required objects
    5.     Dim fs As FileSystemObject
    6.     Dim ts As TextStream
    7.      
    8.     Set fs = New FileSystemObject
    9.  
    10.        'To write
    11.     Set ts = fs.OpenTextFile("C:\mytestfile.txt", ForWriting, True)
    12.     ts.WriteLine "I Love"
    13.     ts.WriteLine "VB Forums"
    14.     ts.Close
    15.      
    16.       'To Read
    17.     If fs.FileExists("C:\mytestfile.txt") Then
    18.         Set ts = fs.OpenTextFile("C:\mytestfile.txt")
    19.          
    20.         Do While Not ts.AtEndOfStream
    21.             MsgBox ts.ReadLine
    22.         Loop
    23.         ts.Close
    24.     End If
    25.  
    26.        'clear memory used by FSO objects
    27.     Set ts = Nothing
    28.     Set fs = Nothing
    29. End Sub
    Last edited by si_the_geek; Mar 27th, 2007 at 10:45 AM. Reason: added explanation (and first two examples) & tidied up. corrected tags after forum upgrade.

Posting Permissions

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



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.