Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read from a text file using VBScript?

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.

like image 418
Curtis Inderwiesche Avatar asked May 12 '09 21:05

Curtis Inderwiesche


1 Answers

Use first the method OpenTextFile, and then...

either read the file at once with the method ReadAll:

Const ForReading = 1
Dim file, content

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

or line by line with the method ReadLine:

Const ForReading = 1
Dim dict, file, row, line

Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", ForReading)
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
like image 56
Jonas Elfström Avatar answered Oct 19 '22 00:10

Jonas Elfström