OpentextFile Permission Denied Error - vbscript

I'm getting an error when i use opentextfile. The problem is weird because it works for a few hundred files then pops up.
Basically the script gets a collection of files, searchs in them for a string which it then removes and writes back the modified content to the same file. The problem occurs when the script wants to open the file again so it can write the modified contents to it.
This is the code:
For Each objFile in colFiles
Set objCurrentFile = objFSO.OpenTextFile(objFile.Path, ForReading)
'Get file contents - exclude end tag '
Do Until objCurrentFile.AtEndOfStream
strLine = objCurrentFile.ReadLine
If InStr(strLine, strSearchTerm) = 0 Then
strNewContents = strNewContents & strLine & vbCrLf
End If
Loop
objCurrentFile.Close
objCurrentFile = nothing
'Write new file contents to existing file '
Set objNewFile = objFSO.OpenTextFile(objFile.Path, ForWriting) 'PROBLEM LINE '
objNewFile.Write strNewContents
objNewFile.Close
objNewFile = nothing
Next

The file is read-only.
Try adding this before you open the text file for writing. If the file is read-only it will remove the read-only attribute.
IsReadOnly = False
IF objFile.Attributes AND 1 Then
objFile.Attributes = objFile.Attributes - 1
IsReadOnly = True
End If
Then add this when you are done writing to the file. If the file was read-only set it back to read-only.
If IsReadOnly Then
objFile.Attributes = objFile.Attributes + 1
IsReadOnly= False
End If

I found the issue. I was opening the text file and then copying it to another folder and then performing more operations on the file before closing the stream.
Once i moved the copy file code to before i opened the stream it works perfectly.
Thanks for the help though, i'll use your code in the future to be safe when working with text files.

you can try givin total control permission to the folder where is the the file to read.

Related

Using HP-UFT, is Is there anyway to tell whether or not an object in the object repository is being used in other tests?

I'm currently using UFT -- I have a GUI test, and there's a web element object in one of my tests I'd like to delete/update, but I'm worried it's being referenced by another test in our test suite. (I am coming into a test suite that someone else built)
Is there anyway to tell whether or not an object in the object repository is being used in other tests? (Without having to go into each individual test and action to find out?)
My way would be simple recursive file search.
Open EditPlus
Search -> Find In Files
Find What =
File Type = *.mts | *.vbs | *.qfl
Folder =
Select the Include Sub Folder Check Box
Click Find
You can use Search>View>Find (or ctrl+F) from UFT and select to look in entire solution
Open "Script.mts" file from every action and search for your object name. If you find the object, write the script name and line number where your object exists, in a file.
Use the below code:
'strScriptsPath is the path where your test script folders are placed.
Set strScripts = objFSO.GetFolder(strScriptsPath).SubFolders
For Each Script In strScripts
strAction = strScriptsPath & "\" & Script.Name & "\Action1\Script.mts"
If objFSO.FileExists(strAction) Then
'Open Script in NotePad
Set strFile = objFSO.OpenTextFile(strAction, 1)
Do While Not (strFile.AtEndOfStream)
strLine = strFile.ReadLine
If InStr(1, strLine, strObjectName) > 0 Then
iVerificationCount = objSheet.UsedRange.Rows.Count
iCurrentRow = iVerificationCount + 1
objSheet.Cells(iCurrentRow, 1) = Script.Name
objSheet.Cells(iCurrentRow, 2) = strLine
If strFile.AtEndOfStream Then
objSheet.Cells(iCurrentRow, 3) = strFile.Line
Else
objSheet.Cells(iCurrentRow, 3) = strFile.Line - 1
End If
End If
Loop
strFile.Close
Set strFile = Nothing
End If
Next
Set strScripts = Nothing
To be able to use this code, declare objFSO object and write a piece of code to create an excel and get objSheet.
You can also replace the object name using the below code:
Use the For Each Loop as mentioned above
strScript = strScriptsPath & "\" & strScriptName & "\Action1\Script.mts"
strFind = "Old Object Name"
strReplace = "New Object Name"
Set strFile = objFSO.OpenTextFile(strScript, 1)
strData = strFile.ReadAll
strNewData = Replace(strData, strFind, strReplace)
strFile.Close
Set strFile = Nothing
Set strFile = objFSO.OpenTextFile(strScript, 2)
strFile.Write strNewData
strFile.Close
Set strFile = Nothing
** You just need to write this entire code in a .vbs file and run that file.

scan computer for a file and output folder location

I need to take a list of computers (IP or PC name) that are all on the same domain in CSV format. Scan each computer for a specific folder name. The folder will be arcXXXof. The x's are a hash and change for each PC. If the folder is found it needs to output the folder path to a CSV and append with each computer scanned. My programming is limited and I only really know Java. Since this will be run from a server it will need local administrative privileges to run on the local machines. My manager suggested I use VBS, but I have never written in that before.
My current snag is getting an error "expected then" Here's my loop.
Sub Recurse(strFolderPath)
Dim objFolder
Set objFolder = objFSO.GetFolder(strFolderPath) 'reads Folders pulled from recursion
Dim objSubFolder
dim folderStart 'grabs the first 2 characters of the file name. Should match 'of' if correct folder
Dim folderEnd 'grabs the last 6 (test) characters of the folder name, should match arc.txt if correct
Global checkEnd
set checkEnd = "arc" 'checks for "arc" at ending
Global checkStart
set checkStart = "of" 'used to check if folder name is correct path
For Each objSubFolder in objFolder 'for every Folder scanned
'Scans the name of the Folder, objSubFolder, for an ending of “arc", and beginning of “of” (testing)
set folderName = objSubFolder.name
Set folderEnd = right(folderName, 3)
set folderStart = left(folderName, 2)
dim folderName
if folderName = testFolderName
then WScript.Echo objSubFolder
'If folderEnd = checkEnd and
'If folderStart = checkStart
'Add Folder location to array, set array to next object
'Then fLocations(i) = object.GetAbsolutePathName(objSubFolder) and i = i+1
else
End If
Next
'recursive for searching new folder
For Each objSubFolder in objFolder.Subfolders
Call Recurse(objSubFolder.Path)
Next
OK, you could use a regex to match the name. Define it up front, in your global scope:
Dim re
Set re = New RegExp
re.IgnoreCase = True
re.Pattern = "^arc\w{3}of$"
I'm using \w, which is equivalent to [a-zA-Z_0-9]. You can change this if you're expecting only digits (\d) or something else for these three chars.
Then, in your Recurse function, test the folder name against it:
For Each objSubFolder in objFolder.SubFolders
' See if this folder name matches our regex...
If re.Test(objSubFolder.Name) Then
' Match. Just display for now...
WScript.Echo objSubFolder.Path
End If
' Test its subfolders...
Recurse objSubFolder.Path
Next
Tip: Remove the On Error Resume Next from your code while you're developing or you might miss all kinds of bugs and cause all kinds of headaches.

unzip file silently vbscript

I found online script that basically unzip every .zip archive in a given path.
sub UnzipAll(path)
set folder = fso.GetFolder(path)
for each file in folder.files
if (fso.GetExtensionName(file.path)) = "zip" then
set objShell = CreateObject("Shell.Application")
objshell.NameSpace(path).CopyHere objshell.NameSpace(file.path).Items
file.delete
end if
next
end sub
This is actually working, but the problem is that I want to unzip "silently" (silently means that I don't want any kind of message from the system when unzipping, like "do you want to overwrite?" ect.).
I've searched a lot on google and I found that you just need to add a few flags on the "CopyHere" method, like this:
objshell.NameSpace(path).CopyHere objshell.NameSpace(file.path).Items, *FLAGHERE*
But the problem is right here. The flags would normally work, but they are completely ignored when unzipping a .zip archive.
So I searched for a workaround, but I didn't find anything helpful.
I managed to do it by myself. Basically you want to unzip 1 file per time and not everyone togheter, and before copying it you just check if it already exists, and evenutally delete it:
set fso = CreateObject("Scripting.FileSystemObject")
sub estrai(percorso)
set cartella = fso.GetFolder(percorso)
for each file in cartella.files
if fso.GetExtensionName(file.path) = "zip" then
set objShell = CreateObject("Shell.Application")
set destinazione = objShell.NameSpace(percorso)
set zip_content = objShell.NameSpace(file.path).Items
for i = 0 to zip_content.count-1
'msgbox fso.Buildpath(percorso,zip_content.item(i).name)+"."+fso.getExtensionName(zip_content.item(i).path)
if (fso.FileExists(fso.Buildpath(percorso,zip_content.item(i).name)+"."+fso.getExtensionName(zip_content.item(i).path))) then
'msgbox "il file esiste, ora lo cancello"
fso.DeleteFile(fso.Buildpath(percorso,zip_content.item(i).name)+"."+fso.getExtensionName(zip_content.item(i).path))
end if
destinazione.copyHere(zip_content.item(i))
next
file.Delete
end if
next
'for each sottocartella in cartella.subfolders
' call estrai(folder.path)
'next
end sub
call estrai("C:\Documents and Settings\Mattia\Desktop\prova")

VBScript to copy file/s beginning with XXX or YYY or ZZZ from directory A to directory B

I have next to zero knowledge on vbs scripting but I have managed to cobble a few together to copy files from one directory to another and delete files in a directory but I've not been able to find anything specifically what I'm now after.
I'm looking to write a vbs script to do the following - copy file/s beginning with XXX or YYY or ZZZ from directory A to directory B.
I've had a look around and cannot quite find what I'm looking for, they all seem far too complex for what I need and involve the latest date or parsing a string within the files etc.
I'm quite sure this is simple but as stated at the top I really do not know what I'm doing so any help would be greatly appreciated.
The following is what I have for copying all files from one directory to another with a progress bar so a amendment to this would be great.
Const FOF_CREATEPROGRESSDLG = &H0&
' copy test 1 to test 2
strTargetFolder = "C:\test2\"
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(strTargetFolder)
objFolder.CopyHere "C:\test1\*.*", FOF_CREATEPROGRESSDLG
Not sure as of yet how to get this in one big progress indicator. Currently it will show progress for each individual file.
Const FOF_CREATEPROGRESSDLG = &H0&
strSourceFolder = "C:\test1\"
strTargetFolder = "C:\test2\"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objSourceFolder = objFSO.GetFolder(strSourceFolder)
Set objFiles = objSourceFolder.Files
Set objShell = CreateObject("Shell.Application")
Set objTargetFolder = objShell.NameSpace(strTargetFolder)
For Each objSingleFile in objFiles
If (InStr(1,objSingleFile.Name,"xxx",vbTextCompare) = 1) Or _
(InStr(1,objSingleFile.Name,"yyy",vbTextCompare) = 1) Or _
(InStr(1,objSingleFile.Name,"zzz",vbTextCompare) = 1) Then
' The file name starts with one the flagged keywords
objTargetFolder.CopyHere objSingleFile.Path, FOF_CREATEPROGRESSDLG
End If
Next
Keep your strTargetFolder code which is used for the actual copy procedure used at the end of the script. Using the FileSystemObject objFSO we cycle through all the files of the directory c:\test1. Each file name is then checked to see if it starts with either of 3 different strings. The comparison is done using vbTextCompare which essentially has it running case insensitive. If a match is found then, using your original code, copy the file to the target directory with progress.
Currently this is not going to recursively navigate all subfolders for file but you could make a recursive function for that.
Use the FileSystemObject in combination with a regular expression:
src = "C:\test1"
dst = "C:\test2"
Set fso = CreateObject("Scripting.FileSystemObject")
Set re = New RegExp
re.Pattern = "^(XXX|YYY|ZZZ)"
For Each f In fso.GetFolder(src).Files
If re.Test(f.Name) Then f.Copy dst & "\"
Next

VBScript/Classic ASP permission denied with fso.OpenTextFile after several uses

I have a process that loops through a moderate amount of data (1MB) storing it in an array and then periodically writes it to the disk. After several iterations, the script fails at fso.OpenTextFile() in my else section as though the file has not been closed or finished closing from the previous time the function was called. The iteration # doesn't seem to be specific as it's happened anywhere between the 2nd and 10th iteration that I can tell. The file is actually created and being appended to so it doesn't appear to be a permissions issue. I considering adding a time delay to the process but don't want to necessarily add overhead to an already long process.
OS: Windows 2012 R2
Any thoughts or suggestions appreciated.
'Write array to disk
sub writeFile()
'on error resumenext
set fso = Server.CreateObject("Scripting.FileSystemObject")
if needToCreateFile then
set objTextFile = fso.CreateTextFile(server.mappath("google/linklist.html"),true)
objTextFile.writeLine("<!DOCTYPE html>")
objTextFile.writeLine("<html>")
objTextFile.writeLine("<title>")
objTextFile.writeLine("Content Listing")
objTextFile.writeLine("</title>")
needToCreateFile = false
else
' OpenTextFile Method needs a Const value
' ForAppending = 8 ForReading = 1, ForWriting = 2
Set objTextFile = fso.OpenTextFile (filename, ForAppending, True)
end if
'Write contents of array to file
for each link in linkList
if link <>"" and not isNull(link) then
objTextFile.writeLine(link & "<br>")
end if
next
objTextFile.writeLine("</html>")
objTextFile.Close
set fso = nothing
set objTextFile = nothing
'on error goto 0
end sub
Follow Up - Solved
Adding a 3 second delay solved the problem, but significantly delayed the processing time. So, rather than opening and closing the file each time I wanted to write to it, I simply left it open until the entire script was done and thus I didn't need the delay.
sub writeFile()
if needToCreateFile then
set objTextFile = fs.CreateTextFile(server.mappath("google/linklist.html"),true)
objTextFile.writeLine("<!DOCTYPE html>")
objTextFile.writeLine("<html>")
objTextFile.writeLine("<title>")
objTextFile.writeLine("Content Listing")
objTextFile.writeLine("</title>")
needToCreateFile = false
end if
'Write contents of array to file
for each link in linkList
if link <>"" and not isNull(link) then
objTextFile.writeLine(link & "<br>")
end if
next
objTextFile.writeLine("</html>")
' objTextFile.Close
' set fso = nothing
' set objTextFile = nothing
end sub
Adding a 3 second delay solved the problem, but significantly delayed the processing time. So, rather than opening and closing the file each time I wanted to write to it, I simply left it open until the entire script was done and thus I didn't need the delay. See modified script above.

Resources