Search code examples
vbscripttext-filesqtphp-uft

How to add line to TOP of text file?


I need to insert a line at the top of a text file. If I use WriteLine() method, it will just append the line to the end of the file.

Btw, I'm using VBScript in QTP (UFT).


Solution

  • Append the content of the text file to your top line, overwrite the text file with the string:

    Option Explicit
    
    Const csFSpec = "31144630.txt"
    Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
    Dim sAll : sAll     = "top line " & Now & vbCrLf
    If goFS.FileExists(csFSpec) Then sAll = sAll & goFS.OpenTextFile(csFSpec).ReadAll()
    goFS.CreateTextFile(csFSpec).Write sAll
    

    output:

    cscript 31144630.vbs
    
    type 31144630.txt
    top line 6/30/2015 7:57:07 PM
    
    cscript 31144630.vbs
    
    type 31144630.txt
    top line 6/30/2015 7:57:25 PM
    top line 6/30/2015 7:57:07 PM