Working with Text Files Tutorials

by CameronM 28. October 2006 01:06

Reading and writing from text files may seem antiquated to the modern developer, after all didn’t we invent database management systems to avoid using flat files in the first place? There are however many times when it is useful and even absolutely necessary to read and write to text files especially when transferring data between legacy systems or proprietary systems that don’t offer direct access to their underlying databases.

Thankfully the FileSystemObject contains a number of excellent methods for opending, reading and writing to text files.

Writing to Text Files

You will find quite a number of examples on the web where the FileSystemObject is not used to write to a text file, which of course works, but to be thorough in our discussion about the FileSystemObject class we’ll look at the slightly more complex using a TextStream.

When you were in the Object Browser you may have noticed that the both the CreateTextFile and OpenTextFile functions of the FileSystemObject class returned a TextStream. We can use this TextStream to add additional lines of data to a new or existing text file.

Creating and Writing to a Text File

'create a new text file and write a line of text
Dim strFileName As String
strFileName = "C:\Temp\MyWorld.txt"

'declare the variables for use with the Scripting library
Dim fso As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream

'create a text file - overwriting any previous file
Set fsoStream = fso.CreateTextFile(strFileName, True)

'write a line to the file
With fsoStream

.WriteLine "Hello World!"

End With

When you were in the Object Browser you may have noticed that the both the CreateTextFile and OpenTextFile functions of the FileSystemObject class returned a TextStream. We can use this TextStream to add additional lines of data to a new or existing text file.

Opening and Writing to a Text File

'open an existing text file and write a line of text
Dim strFileName As String
strFileName = "C:\Temp\MyWorld.txt"

'declare the variables for use with the Scripting library
Dim fso As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream

'create a text file - overwriting any previous file
Set fsoStream = fso.OpenTextFile(strFileName, ForWriting, True)

'write a line to the file
With fsoStream

.WriteLine "Hello World!"

End With

'close the text file
fsoStream.Close

If you run the example above you will notice that no matter how many times you run it, you only end up with one Hello World! in the text file. This is because the ForWriting option, despite the sensible sounding name actually clears the test file when you open it. Not a particularly useful function if you were hoping to keep your previous information. In this case you will need to use the ForAppending option.

Tags: , ,

VBA | Access | VBA