Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleGet and set a file's contents
Keywordsfile, read file, write file
CategoriesFiles and Directories
 
These operations are easy but putting them in simple subroutines makes them much easier to reuse.

To read the file, open it for input and use the Input statement to grab the whole file in one operation.

To write the file, open it for output and use Print to write the file's contents. End the Print statement with a semi-colon to prevent Print from adding an extra carriage return and line feed after the contents.

 
' Get the file's contents.
Private Function GetFileContents(ByVal file_name As String) _
    As String
Dim fnum As Integer

    ' Open the file.
    fnum = FreeFile
    Open file_name For Input As fnum

    ' Grab the file's contents.
    GetFileContents = Input(LOF(fnum), fnum)

    ' Close the file.
    Close fnum
End Function

' Set the file's contents.
Private Sub SetFileContents(ByVal file_name As String, _
    ByVal contents As String)
Dim fnum As Integer

    ' Open the file.
    fnum = FreeFile
    Open file_name For Output As fnum

    ' Write the file's contents (without an
    ' extra trailing vbCrLf).
    Print #fnum, contents;

    ' Close the file.
    Close fnum
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated