Read and write into a file using VBScript

Maddy picture Maddy · Jul 17, 2009 · Viewed 265.8k times · Source

How can we read and write some string into a text file using VBScript? I mean I have a text file which is already present so when I use this code below:-

Set fso = CreateObject("Scripting.FileSystemObject" )            
Set file = fso.OpenTextFile("C:\New\maddy.txt",1,1) 

This opens the file only for reading but I am unable to write anything and when I use this code:-

Set fso = CreateObject("Scripting.FileSystemObject" )            
Set file = fso.OpenTextFile("C:\New\maddy.txt",2,1)

I can just use this file for writing but unable to read anything. Is there anyway by which we can open the file for reading and writing by just calling the OpenTextFile method only once.

I am really new to VBScript. I am only familiar with C concepts. Is there any link to really get me started with VBScript?

I guess I need to have a good knowledge of the objects and properties concepts.

Answer

ghostdog74 picture ghostdog74 · Jul 17, 2009

You can create a temp file, then rename it back to original file:

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file.txt"
strTemp = "c:\test\temp.txt"
Set objFile = objFS.GetFile(strFile)
Set objOutFile = objFS.CreateTextFile(strTemp,True)
Set ts = objFile.OpenAsTextStream(1,-2)
Do Until ts.AtEndOfStream
    strLine = ts.ReadLine
    ' do something with strLine 
    objOutFile.Write(strLine)
Loop
objOutFile.Close
ts.Close
objFS.DeleteFile(strFile)
objFS.MoveFile strTemp,strFile 

Usage is almost the same using OpenTextFile:

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file.txt"
strTemp = "c:\test\temp.txt"
Set objFile = objFS.OpenTextFile(strFile)
Set objOutFile = objFS.CreateTextFile(strTemp,True)    
Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine
    ' do something with strLine 
    objOutFile.Write(strLine & "kndfffffff")
Loop
objOutFile.Close
objFile.Close
objFS.DeleteFile(strFile)
objFS.MoveFile strTemp,strFile