VB Script can create and read text files only. It cannot create or read binary files such as images or movie files. A file can be created using the 'CreateTextFile' function. This function will return a 'TextStreamObject' which can be used to write data into the file. The syntax of the 'CreateTextFile' function is given below
Syntax: CreateTextFile filename [, overwrite[, unicode]]
Here the argument 'filename' is a mandatory argument. It specifies the name of the file to be created with the complete path.
The 'overwrite' argument is an optional argument. Its a boolean argument which will take either 'True' or 'False'. If 'True' is specified then if a file with the same name exists, it will be overwritten. If 'False' is specified then if a file with the same exists then vbscript will produce an error. The default value of this argument is 'True'.
The 'unicode' argument is also an optional argument. Its a boolean argument which will take either 'True' or 'False'. This argument decides whether the file should be considered as an ASCII file or a 'UNICODE' file. 'True' means 'UNICODE' and 'False' means 'ASCII'. The default value of this argument is 'False' (File will be created as an ASCII file)
Now the since the second and thrid argument is optional and both are boolean values, if you want to specify the third argument, you have to specify the first, second and third argument.
The following code create a text file with a given file name. If a file exists in the same location with the same file name, it will be overwritten.
Dim ObjFso
Dim StrFileName
On Error Resume Next
StrFileName = "C:\TestFile.txt"
Set ObjFso = CreateObject("Scripting.FileSystemObject")
ObjFso.CreateTextFile(StrFileName, False)
If Err.Number = 0 Then
WScript.Echo("File successfully created.")
Else
WScript.Echo("File cannot be created because of some other reason")
End If
Dim ObjFso
Dim StrFileName
On Error Resume Next
StrFileName = "C:\TestFile2.txt"
Set ObjFso = CreateObject("Scripting.FileSystemObject")
ObjFso.CreateTextFile StrFileName, False
If Err.Number = 0 Then
WScript.Echo("File successfully created.")
Else
WScript.Echo("File with the same name exists!!.")
End If
Dim ObjFso
Dim StrFileName
On Error Resume Next
StrFileName = "C:\TestFile2.txt"
Set ObjFso = CreateObject("Scripting.FileSystemObject")
ObjFso.CreateTextFile StrFileName, True, True
If Err.Number = 0 Then
WScript.Echo("File successfully created.")
Else
WScript.Echo("File with the same name exists!!.")
End If