Login   /   Register

Add a line to the top of a text file

Rate this article
     0 votes, average: 0 out of 50 votes, average: 0 out of 50 votes, average: 0 out of 50 votes, average: 0 out of 50 votes, average: 0 out of 5
Loading ... Loading ...
April 1st, 2008 by daniva

ForReading and ForWriting – that we’ll use when working with our text file.

Const ForReading = 1
Const ForWriting = 2
 
fileName = "C:\MyFolder\Test.txt"
Set fso = CreateObject( "Scripting.FileSystemObject" )
Set textFile = fso.OpenTextFile(fileName, ForReading )
 
contents = textFile.ReadAll
textFile.Close
firstLine = "This is the new first line in the text file."
newContent = firstLine & vbCrLf & contents
 
Set textFile = fso.OpenTextFile( fileName, ForWriting  )
textFile.WriteLine newContent
textFile.Close

We create an instance of the FileSystemObject and then use the OpenTextFile method to open the file C:\MyFolder\Test.txt for reading:

Set textFile = fso.OpenTextFile(fileName, ForReading )

Now that the file is open, we use the ReadAll method to read the entire contents of the file and store those contents in a variable named contents. We then immediately close the file Test.txt. Why? Well, the FileSystemObject allows you to open a file for reading or for writing, but you cannot do both at the same time. To add a new line to the top of the file, we’re going to have to write to the file; that means we’ll have to reopen it, but for writing.

Next, we need to construct the new contents for the file. We can’t directly add a line to the top of the text file; the FileSystemObject only allows you to add new lines to the end of a text file. Therefore, what we’ll have to do is create an entirely new file in memory and then replace the existing contents of Test.txt with this new file. Our new file will consist of three parts: a new first line; a carriage return-linefeed; and the existing contents of the file. To construct this file we start off by using this code to store the new first line in a variable named firstLine:

firstLine = "This is the new first line in the text file."

We then use this line of code to concatenate the new first line, a carriage return-linefeed (using the VBScript constant vbCrLf) and the existing contents of the file (which we stored in the variable contents):

newContent = firstLine & vbCrLf & contents

All that’s left now is to reopen Test.txt (for writing this time), then use the WriteLine method to replace the exiting contents with our new file:

Set textFile = fso.OpenTextFile( fileName, ForWriting  )
textFile.WriteLine newContent

We then call the Close method

Based on "How Can I Add a Line to the Top of a Text File?" from the Scripting Guys

Posted in VBScript

Leave a Reply

You must be logged in to post a comment.

This article was viewed 671 times