Introduction - Using FSO methods to create text files
The Key to using VBScripts to create and manipulate files is to learn the
best methods to manipulate the FSO (File System Object).
FSO Topics
Here is a VBScript to
make a text file. Once you have created the file, use the WriteLine method
to add text. Whilst this may seem a cumbersome way of manipulating files,
the learning points will help you create scripts which can automate reading and
writing to files, Active Directory or the registry.
'VBScript
'CreateTextFile method to add text to a file
DIM fso, NewsFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set NewsFile = fso.CreateTextFile("c:\ezine\bestpractice3.txt", True)
NewsFile.WriteLine("Best practice tips")
NewsFile.Write ("Use Remarks to show the purpose of your script.")
NewsFile.Write (" Remember to clear up at the end of the script.")
NewsFile.Close
In our script example, fso (FileSystemObject) creates an object which we can
manipulate. I
have chosen the CreateTextFile method here, but be aware that there are other
methods like CreateFolder or DeleteFile. Once you have created the file as a TextStream object, then we can start doing some useful work.
To get text into
the file, I have selected two methods to append data to the file, WriteLine and Write. WriteLine
adds a carriage return and so makes a complete line of text. Whereas write, just adds
text but creates no end of line marker.
Finally, good practice is to tidy up with a Close statement.
Note: Trap for you in the above script.
Change the path on line 7. Point it to a folder on your
machine.
Set NewsFile = fso.CreateTextFile("c:\ezine\bestpractice3.txt", True)
Here is a variation of the CreateTextFile method which adds three blank lines
between your text. The crucial new command is WriteBlankLines
'VBScript
'CreateTextFile method to add text to a file
DIM fso, NewsFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set NewsFile = fso.CreateTextFile("c:\ezine\bestpractice4.txt", True)
NewsFile.WriteLine("Best practice tips")
NewsFile.Write ("Use Remarks to show the purpose of your script.")
NewsFile.Write (" Remember to clear up at the end of the script.")
NewsFile.WriteBlankLines 3 NewsFile.WriteLine("WriteBlankLines method
produced the gap")
NewsFile.Close
- CreateFolder
- CopyFile
- GetFile
- OpenTextFile
|