OpentextFile 权限被拒绝错误

问题描述 投票:0回答:3

我使用 opentextfile 时遇到错误。这个问题很奇怪,因为它适用于几百个文件然后弹出。

基本上,脚本获取文件集合,在其中搜索字符串,然后删除该字符串并将修改后的内容写回同一文件。当脚本想要再次打开文件以便将修改的内容写入其中时,就会出现问题。

这是代码:

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
vbscript
3个回答
0
投票

该文件是只读的。
在打开文本文件进行写入之前尝试添加此内容。
如果文件是只读的,它将删除只读属性。

IsReadOnly = False
IF objFile.Attributes AND 1 Then
    objFile.Attributes = objFile.Attributes - 1
    IsReadOnly = True
End If

写入文件完成后添加此内容。
如果文件是只读的,请将其恢复为只读。

If IsReadOnly Then
    objFile.Attributes = objFile.Attributes + 1
    IsReadOnly= False
End If

0
投票

我发现了问题。我打开文本文件,然后将其复制到另一个文件夹,然后在关闭流之前对文件执行更多操作。

一旦我将复制文件代码移至打开流之前,它就可以完美运行。

感谢您的帮助,我将来会使用您的代码以确保处理文本文件时的安全。


0
投票

您可以尝试授予要读取文件的文件夹的完全控制权限。

© www.soinside.com 2019 - 2024. All rights reserved.