WinBatch Tech Support Home

Database Search

If you can't find the information using the categories below, post a question over in our WinBatch Tech Support Forum.

TechHome

System_IO

Can't find the information you are looking for here? Then leave a message over on our WinBatch Tech Support Forum.

Find Text in Multiple Files

 Keywords:  FindInFiles Microsoft.VisualBasic System.IO Find Files

;; What to look for and where to look.
strText =  'WinBatch'   ; Your text here
strDir  =  'c:\logs'    ; Your search location here
aMask[0] = '*.log'      ; Your file type(s) here.
;; aMask[1] = '*.txt'

ObjectClrOption('useany', 'Microsoft.VisualBasic')
objFileSys = ObjectClrNew('Microsoft.VisualBasic.FileIO.FileSystem')
SrchOpt = ObjectClrType('Microsoft.VisualBasic.FileIO.SearchOption', 3) ; 3 = search subdirs.

ObjectClrOption('useany', 'System.IO')

;; Since the FindInFiles method is overloaded the CLR binder needs a bit
;; of help identifying which version of the method we are using. This
;; is accomplished by creating a variant array of bstr using the "array|bstr"
;; type indicator in the method call.

;; Search for file swith the extension '.txt'.
Files = objFileSys.FindInFiles(strDir , strText, bool:@true, SrchOpt, array|bstr:aMask)
aMap = MapCreate()
ForEach File In Files

  ;; WIL FileOpen, FileRead, FileClose or BinaryRead may be faster here but
  ;; using FCL class for example consistency's sake.
  objReader = ObjectClrNew('System.IO.StreamReader', File)
  strLine = objReader.ReadLine()
  lLines = ''
  While  !objReader.EndOfStream
     If StrIndexNC(strLine, strText, 0, @fwdscan )
        ; This example just saves the line but you could create
        ; line snippits here.
        lLines := strLine:@lf
     EndIf
     strLine = objReader.ReadLine()
  EndWhile
  objReader.Close()

  ;; Perform whatever here to store the information.
  If lLines != ''
     aMap[File] = lLines
  EndIf
Next

; Show the results.
If ArrInfo(aMap, 1)
   strText = ''
   ForEach File In aMap
      strText := File:@lf
      strText := aMap[File]:@lf
   Next

   Message('Found File Names and Lines', strText)
Else
   Message('Find in Files', 'Nothing found')
EndIf
Exit

Article ID:   W18533
Filename:   Find Text in Files.txt
File Created: 2019:09:18:11:16:34
Last Updated: 2019:09:18:11:16:34