9
votes

I am looking to see a simple way to read from and write to a text file using VBScript.

I think this is an acceptable method for writing to a file.

 Dim f, 
 Dim fso

 Set fso = CreateObject("Scripting.FileSystemObject")
 Set f = fso.CreateTextFile("C:\test.txt", True, True)

 f.WriteLine("Data to Add to file.")
 f.Close

However, I would like to know how to read from a file in a similar fashion.

2
I don't understand. Isn't that what you just did, except you're not using the read methods? - johnny
Yes, but that will only work for one line. - Curtis Inderwiesche
So use the ReadAll method instead - Tmdean
WriteLine writes one line. ReadLine reads one line. ReadAll to read whole file (or Read(fileObj.Size)), Write to write all contents. - Zimba

2 Answers

31
votes

Use first the method OpenTextFile, and then...

either read the file at once with the method ReadAll:

Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll

or line by line with the method ReadLine:

Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
  line = file.Readline
  dict.Add row, line
  row = row + 1
Loop

file.Close

'Loop over it
For Each line in dict.Items
  WScript.Echo line
Next
0
votes
Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")

' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close

' Write file
outFile.write (strRetVal)
outFile.Close