vbscript how to open a file and read/write to it

AntonInf used Ask the Experts™
hi there

i want to know how to open and read/write to a file in vbscript. i search and purchased tutorials but they havent shown me. can someone help

thank you for your support
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
What sort of file? If it's a simple text file, use File System Object.
Here is a sample script that copies a text file.  It will either overwrite the original file or create a new one depending on how many filenames are specified on the command line when you run it.

Save this script in a file named filecopy.vbs (or whatever you want) and run it like this:    vbscript filecopy.vbs file1 file2

If you only give it one file name it will overwrite that file (since the script does not make any changes to the content it doesn't really serve any purpose other than to demonstrate the file opening, reading, writing, and closing features of the File System Object.

' Define needed constants
Const ForReading = 1
Const ForWriting = 2
Const TriStateUseDefault = -2

' Get input file name from command line parm, if 2 parms entered
' use second as new output file, else rewrite to input file
If (WScript.Arguments.Count > 0) Then
    sInfile = WScript.Arguments(0)
    WScript.Echo "No filename specified."
End If
If (WScript.Arguments.Count > 1) Then
    sOutfile = WScript.Arguments(1)
    sOutfile = sInfile
End If

' Create file system object
Set oFSO = CreateObject("Scripting.FileSystemObject")

' Read entire input file into a variable and close it
Set oInfile = oFSO.OpenTextFile(sInfile, ForReading, False, TriStateUseDefault)
sData = oInfile.ReadAll

' Write the file
Set oOutfile = oFSO.OpenTextFile(sOutfile, ForWriting, True)

Open in new window

Bill PrewIT / Software Engineering Consultant
Top Expert 2016
The code that JesterToo posted above is how I usually do it, using the FileSystem object.  In between the lines of code that read the file, and the lines that write the file you would typically have logic that processed the array of lines from the input file, building the output you want.  For an example take a look at my accepted solution in the following older question on this site:

For additional learning and info on the FileSystem object usage take a look at these pages that explain in more detail.



thank you

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial