编辑文件夹中的每个文件

Edit each file in a folder

我有一个函数可以替换文本文件中的特定字符串。这适用于特定文件 (test.conf),没有任何问题。但是现在我正在寻找一种方法来检查目录中每个文件的这个字符串。有没有办法检查目录中的所有文件并查找并替换每个文件中的字符串?我不太确定如何使用 For Each File 函数。

Set objFile = objFSO.OpenTextFile(operations & "\test.conf", ForReading)
strText = objFile.ReadAll
objFile.Close
strText = Replace(strText, "$$Username:$$", username)
Set objFile = objFSO.OpenTextFile(operations & "\test.conf", ForWriting)
objFile.WriteLine strText
objFile.Close

这是我针对特定文件 "test.conf" 的解决方案。 但是此文件夹中可能有更多文件,其中包含 $$Username:$$ 字符串。

示例:

\FOLDER\test.conf
\FOLDER\abc.conf
\FOLDER\def.conf
...

尝试像这样遍历每个 .conf 文件:

Option Explicit

Const ForReading = 1
Const ForWriting = 2

dim sFolder : sFolder = "C:\Temp\"
dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
dim oFile, objFile, strText

For Each oFile In oFSO.GetFolder(sFolder).Files
  If UCase(oFSO.GetExtensionName(oFile.Name)) = "CONF" Then

    Set objFile = oFSO.OpenTextFile(oFile.Path, ForReading)
    strText = objFile.ReadAll
    objFile.Close
    Set objFile = Nothing

    strText = Replace(strText, "texttoreplace", "newtext")
    Set objFile = oFSO.OpenTextFile(oFile.Path, ForWriting)
    objFile.WriteLine strText
    objFile.Close
    Set objFile = Nothing

  End if
Next

Set oFSO = Nothing