tags:

views:

591

answers:

2

Hi

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

A: 

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
Tester101
A: 

Hi

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.