VB6.0 遍历指定文件夹所有文件,查找某字符串替换成新的

把某文件夹下的,包括子文件夹,遍历所有格式的文件,查找某字符串比如“123123123sd” 替换成自己指定的字符串。谢谢!
最好是替换后原文件能正常工作,要用到进制替换?

整个过程可以分为两步:

一、递归遍历目录;

二、逐个处理文件。

至于是否用到进制替换要看你的目的,要看“123123123sd”这个字符串的性质。

个人认为需要过滤下文件类型。例如TXT,HTML,INI,ASP,PHP ,JS等等这些类型的文件内容都是字符串性质。但是,读很多格式的复杂文件,要通过二进制流方式,那么读到的可能不是“123123123sd”这种形式。

以下是演示代码,仅供参考。

Option Explicit
Private FileCount As Long, lcount As Long  '文件计数

Private Sub Command1_Click()
    DirFolder "E:\Web"
    MsgBox "共扫描了" & FileCount & "个文件!找到了" & lcount & "行"
End Sub
Private Function DirFolder(FolderPath As String) As Long
     On Error Resume Next
     Dim FSO, F, Folder, MulitFolder, File, MulitFile, Path As String
     Set FSO = CreateObject("Scripting.FileSystemObject")
     Set F = FSO.GetFolder(FolderPath)
     Set MulitFolder = F.SubFolders
     For Each Folder In MulitFolder
        Path = FolderPath & "\" & Folder.Name & "\"
        Set MulitFile = Folder.files
        For Each File In MulitFile           '文件处理
            If GetType(Path & File.Name) = "php" Then   '文件类型过滤,
                Me.Cls: Print "正在处理:" & Path & File.Name  '显示
                List1.AddItem Path & File.Name  '加载到列表
                FileCount = FileCount + 1       '文件计数
                '**********此处添加文件处理函数*************
                DealFlie Path & File.Name  '自定义函数
                '***********************************
            End If
            DoEvents
        Next
        Call DirFolder(FolderPath & "\" & Folder.Name)  '递归调用
     Next
End Function
'文件处理函数示例
Private Function DealFlie(FileName As String) As Long
    Dim n As Integer, s As String
    n = FreeFile()
    Open FileName For Input As #n
        While Not EOF(n)
            Input #121, s
            If InStr(s, "123123123sd") <> 0 Then
                lcount = lcount + 1
            End If
        Wend
    Close #n
End Function
'获取文件后缀
Private Function GetType(src As String) As String
    Dim i As Long
    For i = Len(src) To 1 Step -1
        If Mid(src, i, 1) = "." Then Exit For
    Next i
    GetType = Mid(src, i + 1)
End Function

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-12-21
这个替换只能针对文本文件吧。 如果是exe的怎么替换??

文本替换的话直接用replace就可以了
第2个回答  2013-12-20
这个不算难,但有必要写这程序嘛,UltraEdit等工具轻松搞定这事儿。
如果你是想写程序练手,那是另一回事,坚决支持。
第3个回答  2013-12-20
开玩笑了吧,能遍历到文件里的字符串?我期待......
第4个回答  2013-12-20
是替换文件名还是替换文件内容里的这个字符串追问

替换文件内容里的这个字符串

相似回答