Closing a file in a VBScript (VBS) program usually means closing the file handle your script opened—not closing the .vbs script itself. If your script uses the FileSystemObject to read or write a file, call the file object’s Close method when you are finished. Closing the handle helps save pending changes, release file locks, and prevent other programs from being blocked from using the file.
This guide explains how to close a file in VBScript, with examples for reading, writing, and appending text. It also covers common errors, cleanup practices, and how to stop a running VBS script when you mean “close” the program rather than a data file.
What Does “Close a VBS File” Mean?
The phrase “close a VBS file” can refer to a few different things. A VBScript file is a script saved with the .vbs extension. When Windows runs the script, the script itself is managed by the Windows Script Host. In most cases, you do not need to call a special command to close the .vbs file after it runs.
More often, the script opens a separate data file, such as a text file or log. That opened file is represented by an object, and your script should close that object when it has finished reading or writing. With the FileSystemObject, the object is usually a TextStream, and the correct method is Close.
-
Close a data file: Call
Closeon the TextStream object. -
Stop a running script: Use
WScript.Quitor close the Windows Script Host process. - Close a script in an editor: Close the editor window or tab. This is separate from VBScript file handling.
How to Close a File in VBScript
First, create a FileSystemObject and use it to open a file. Store the returned TextStream object in a variable. After you have finished working with the file, call Close on that variable.
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("C:\Scripts\notes.txt", 1)
Do Until file.AtEndOfStream
line = file.ReadLine
WScript.Echo line
Loop
file.Close
Set file = Nothing
Set fso = Nothing
In this example, the second argument to OpenTextFile is 1, which opens the file for reading. The loop reads each line, and file.Close releases the file after the last line has been processed. The variables are then set to Nothing to release their object references.
Use Close on the same TextStream object returned by OpenTextFile. The method does not take a filename as an argument. For example, file.Close is correct, while fso.Close("C:\Scripts\notes.txt") is not the way to close a FileSystemObject file stream.
Close a File After Writing to It
When writing text, closing the stream is especially important. It gives the script an opportunity to finish writing buffered data and release its access to the file. If the script exits without closing the stream, the operating system will eventually clean up the process, but relying on that is not good file-handling practice.
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.CreateTextFile("C:\Scripts\report.txt", True)
file.WriteLine "Daily report"
file.WriteLine "The script completed successfully."
file.Close
Set file = Nothing
Set fso = Nothing
CreateTextFile creates a TextStream for writing. The second argument, True, allows the script to overwrite an existing file. If you do not want to overwrite existing content, use False instead, or choose another method that fits your requirements. Always confirm the destination path before running a script that can replace a file.
You can also open a file for writing with OpenTextFile. Its mode constants are commonly represented by numbers: 1 for reading, 2 for writing, and 8 for appending. When using the write or append modes, close the TextStream after the final write operation.
Close a File Opened for Appending
Appending adds new content to the end of a file instead of replacing its existing contents. This is useful for logs, status updates, and simple audit trails. The following example opens a log file in append mode and closes it when the message has been added.
Set fso = CreateObject("Scripting.FileSystemObject")
Set logFile = fso.OpenTextFile("C:\Scripts\activity.log", 8, True)
logFile.WriteLine Now & " - Script started"
logFile.Close
Set logFile = Nothing
Set fso = Nothing
The third argument, True, tells OpenTextFile to create the file if it does not already exist. The file is still closed with the Close method. Keep a reference to the stream object so that you can close it after writing.
Use Constants to Make File Modes Easier to Read
Numbers such as 1 and 8 work, but named constants make the code easier to understand. You can define the values near the top of your script and use the names when opening files.
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("C:\Scripts\notes.txt", ForReading)
text = file.ReadAll
file.Close
WScript.Echo text
Set file = Nothing
Set fso = Nothing
VBScript does not require you to use these constant names, but they can make it clearer what the script is doing. Whichever form you choose, remember that opening a file creates a stream that should be closed when your work is complete.
Close Files Safely When an Error Occurs
A script can encounter an error after opening a file but before reaching its normal Close statement. For example, a destination folder may be missing, a file may be unavailable, or a later operation may fail. A basic cleanup section can help ensure that an open stream is closed before the script exits.
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("C:\Scripts\output.txt", 2, True)
If Err.Number <> 0 Then
WScript.Echo "Could not open the file: " & Err.Description
WScript.Quit 1
End If
file.WriteLine "Processing complete"
If Err.Number <> 0 Then
WScript.Echo "Could not write to the file: " & Err.Description
Err.Clear
End If
If Not file Is Nothing Then
file.Close
End If
Set file = Nothing
Set fso = Nothing
On Error Resume Next tells VBScript to continue after an error, so use it carefully. Check Err.Number after operations that can fail, and handle the problem deliberately. Avoid leaving error handling enabled across large sections of a script without checking for errors; otherwise, failures can be hidden and the script may appear to succeed when it has not.
For a larger script, put file cleanup in a clearly marked section and route expected failure paths through it. That makes it easier to see that every successfully opened stream is closed. Do not call Close on a variable that was never assigned a valid TextStream object.
Close More Than One Open File
If your script opens multiple files, each stream needs its own Close call. Keep the file objects in separate variables and close each one after its work is complete. This is especially important when writing several reports or reading from one file while writing to another.
Set fso = CreateObject("Scripting.FileSystemObject")
Set source = fso.OpenTextFile("C:\Scripts\source.txt", 1)
Set destination = fso.CreateTextFile("C:\Scripts\copy.txt", True)
Do Until source.AtEndOfStream
destination.WriteLine source.ReadLine
Loop
source.Close
destination.Close
Set source = Nothing
Set destination = Nothing
Set fso = Nothing
Close both streams even if one is used only for reading. A file opened for reading can still be held open by the script, which may interfere with another process that needs to rename, replace, or access it.
How to Stop a Running VBS Script
If you mean that you want to close or stop the script itself, use WScript.Quit. This ends the current Windows Script Host session. You can optionally provide an exit code: 0 commonly indicates success, while a nonzero value can indicate an error.
WScript.Echo "The task is complete."
WScript.Quit 0
When a script is running in a command window through cscript.exe, you can usually stop it by pressing Ctrl+C in that window. A script launched with wscript.exe may show a Windows dialog or run without a visible console, depending on how it was started. You can close the related Windows Script Host process through Task Manager if needed, but ending a process should be a last resort because it can interrupt unfinished work.
If the script has open data files, close those streams before calling WScript.Quit. For example, write any final output, call file.Close, and then end the script. This gives the script a clean shutdown rather than relying on process termination to release resources.
Common Mistakes When Closing a VBS File
-
Closing the wrong object: Call
Closeon the TextStream returned by the file-opening method, not on the FileSystemObject. - Forgetting to close after writing: Close the stream after the final write so the file is released promptly.
- Using a variable that was never set: If opening the file failed, the stream object may not be available to close.
-
Assuming
Set file = Nothingreplacesfile.Close: Releasing the object reference is not a substitute for explicitly closing the stream. -
Calling
WScript.Quittoo early: End the script only after closing any files it opened and completing required cleanup. - Using the wrong file mode: Reading, writing, and appending use different modes, so select the one that matches your task.
Frequently Asked Questions
Do I need to close a .vbs file from inside itself?
Usually, no. Windows Script Host runs the script and manages its execution. You generally need to close data files that the script opens, not the script file currently being executed.
What is the VBScript command to close a text file?
For a TextStream object, use file.Close, replacing file with the name of your object variable.
Can I close a file by setting its variable to Nothing?
Set the object variable to Nothing after calling Close. The explicit close releases the stream in a clear and predictable way; clearing the variable helps release your reference to the object.
Why is another program unable to use my file?
Your script may still have the file open. Check that every TextStream is closed on all normal and error paths, and confirm that another program is not holding the file.
Conclusion
To close a file in VBScript, call the Close method on the TextStream object returned by OpenTextFile or CreateTextFile. Close each stream after reading or writing, handle errors carefully, and set object variables to Nothing when you no longer need them. If you mean stopping the running VBS script instead, close its data files first and then use WScript.Quit. Following these simple steps helps prevent file locks, incomplete output, and avoidable VBScript errors.
Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.