|
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
Dim strFileName As String
strFileName = "C:\Temp\MyWorld.txt"
Dim fso As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Set fsoStream = fso.CreateTextFile(strFileName, True)
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
Dim strFileName As String
strFileName = "C:\Temp\MyWorld.txt"
Dim fso As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Set fsoStream = fso.OpenTextFile(strFileName, ForWriting, True)
With fsoStream
.WriteLine "Hello World!"
End With
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.
Other Topics about Using the FileSystemObject
Getting Information About Your Drives
Getting Information About Your Folders
Getting Information About Your Files
Reading from Text Files
|