Vbscript : fso.opentextfile permission denied

file-permissionsvbscript

In my code segment, when I script the file name, it gives me a permission denied
on the following line:

Set objTextFile = objFSO.OpenTextFile(strDirectory & strFile, ForAppending, True)

Here is the script

'output log info
Function OutputToLog (strToAdd)  
    Dim strDirectory,strFile,strText, objFile,objFolder,objTextFile,objFSO
    strDirectory = "c:\eNet"
    strFile = "\weeklydel.bat"
    'strText = "Book Another Holiday"
    strText = strToAdd

    ' Create the File System Object
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    ' Check that the strDirectory folder exists
    If objFSO.FolderExists(strDirectory) Then
       Set objFolder = objFSO.GetFolder(strDirectory)
    Else
       Set objFolder = objFSO.CreateFolder(strDirectory)
       'WScript.Echo "Just created " & strDirectory
    End If

    If objFSO.FileExists(strDirectory & strFile) Then
       Set objFolder = objFSO.GetFolder(strDirectory)
    Else
       Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
       'Wscript.Echo "Just created " & strDirectory & strFile
    End If

    set objFile = nothing
    set objFolder = nothing
    ' OpenTextFile Method needs a Const value
    ' ForAppending = 8 ForReading = 1, ForWriting = 2
    Const ForAppending = 2

    Set objTextFile = objFSO.OpenTextFile(strDirectory & strFile, ForAppending, True)

    ' Writes strText every time you run this VBScript
    objTextFile.WriteLine(strText)
    objTextFile.Close
End Function

I have assigned the vbscript domain administrator permissions. Any ideas?

thanks in advance

Best Answer

I don't think this has to do with File Permissions per se. It has to do with the fact that you've created the file using:

Set objFile = objFSO.CreateTextFile(strDirectory & strFile)

That creates the file...and carries a reference to that file (objFile)

Then you don't close the file before you destroy the reference

...
'Missing objFile.Close here
Set objFile = nothing
Set objFolder = nothing
...

Consequently you're destroying the reference but leaving the textstream open in memory thus locking your file.

You are then proceeding to attempt to re-open the file while the file is already "open". This is a little long winded, you've already got a reference after you've created the file - it would be easier just to write straight to that rather than destroy the reference before creating another one.

Related Topic