Baeb
Baeb

Reputation: 21

VBScript can create text file but can't delete file (permission denied)?

I create a .vbs file (that can: creat text file -> Open notepad.exe -> delete the file above) like this:

' Create a new file
Dim objFS, objFile
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.CreateTextFile("D:\Folder\Textfile.txt")
objFile.WriteLine ("sample text")

' Run a program and wait
WScript.CreateObject("WScript.Shell").Run "notepad.exe", 1, true

' Delete file
objFS.Deletefile("D:\Folder\Textfile.txt")

But when I run it, after close notepad window, it show error message:

Line: 10
Char: 1
Error: Permission denied
Code: 800A0046
Source: Microsoft VBScript runtime error

I don't know why this .vbs can't not delete the text file? Thank you for any help!

Upvotes: 2

Views: 12381

Answers (1)

Flakes
Flakes

Reputation: 2442

You have to close the file handle in the script before trying to delete it.

' Create a new file
Dim objFS, objFile
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.CreateTextFile("D:\Folder\Textfile.txt")

'write to the file
objFile.WriteLine ("sample text")

'close the file
objFile.close
set objFile = Nothing

' open the file in notepad, and wait
WScript.CreateObject("WScript.Shell").Run "notepad.exe D:\Folder\Textfile.txt", 1, true

' Delete file
objFS.Deletefile("D:\Folder\Textfile.txt")

set objFS = Nothing

Upvotes: 6

Related Questions