Search for files on harddisk

Posted on 2003-10-28
Last Modified: 2010-05-03

I need to make a program in VB that searches for the existens of a file(s) on the hard disk(s).
If for examples kill.exe and tlist.exe exists then msgbox "Warning".
The files to search for must came from a file, for example filenames.txt

Is that possible?

Question by:harryv

Accepted Solution

fantasy1001 earned 200 total points
ID: 9640229
This is an example of searching you need. Create a file named input.txt in c:\ which contain the filename you want to search. Each filename is separate by newline

Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long
Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long

Const MAX_PATH = 260

Private Type FILETIME
    dwLowDateTime As Long
    dwHighDateTime As Long
End Type

Private Type WIN32_FIND_DATA
    dwFileAttributes As Long
    ftCreationTime As FILETIME
    ftLastAccessTime As FILETIME
    ftLastWriteTime As FILETIME
    nFileSizeHigh As Long
    nFileSizeLow As Long
    dwReserved0 As Long
    dwReserved1 As Long
    cFileName As String * MAX_PATH
    cAlternate As String * 14
End Type
Function StripNulls(OriginalStr As String) As String
    If (InStr(OriginalStr, Chr(0)) > 0) Then
        OriginalStr = Left(OriginalStr, InStr(OriginalStr, Chr(0)) - 1)
    End If
    StripNulls = OriginalStr
End Function

Function FindFilesAPI(path As String, SearchStr As String, FileCount As Integer, DirCount As Integer)
    'KPD-Team 1999

    Dim FileName As String ' Walking filename variable...
    Dim DirName As String ' SubDirectory Name
    Dim dirNames() As String ' Buffer for directory name entries
    Dim nDir As Integer ' Number of directories in this path
    Dim i As Integer ' For-loop counter...
    Dim hSearch As Long ' Search Handle
    Dim Cont As Integer
    If Right(path, 1) <> "\" Then path = path & "\"
    ' Search for subdirectories.
    nDir = 0
    ReDim dirNames(nDir)
    Cont = True
    hSearch = FindFirstFile(path & "*", WFD)
    If hSearch <> INVALID_HANDLE_VALUE Then
        Do While Cont
        DirName = StripNulls(WFD.cFileName)
        ' Ignore the current and encompassing directories.
        If (DirName <> ".") And (DirName <> "..") Then
            ' Check for directory with bitwise comparison.
            If GetFileAttributes(path & DirName) And FILE_ATTRIBUTE_DIRECTORY Then
                dirNames(nDir) = DirName
                DirCount = DirCount + 1
                nDir = nDir + 1
                ReDim Preserve dirNames(nDir)
            End If
        End If
        Cont = FindNextFile(hSearch, WFD) 'Get next subdirectory.
        Cont = FindClose(hSearch)
    End If
    ' Walk through this directory and sum file sizes.
    hSearch = FindFirstFile(path & SearchStr, WFD)
    Cont = True
    If hSearch <> INVALID_HANDLE_VALUE Then
        While Cont
            FileName = StripNulls(WFD.cFileName)
            If (FileName <> ".") And (FileName <> "..") Then
                FindFilesAPI = FindFilesAPI + (WFD.nFileSizeHigh * MAXDWORD) + WFD.nFileSizeLow
                FileCount = FileCount + 1
            End If
            Cont = FindNextFile(hSearch, WFD) ' Get next file
        Cont = FindClose(hSearch)
    End If
    ' If there are sub-directories...
    If nDir > 0 Then
        ' Recursively walk into them...
        For i = 0 To nDir - 1
            FindFilesAPI = FindFilesAPI + FindFilesAPI(path & dirNames(i) & "\", SearchStr, FileCount, DirCount)
        Next i
    End If
End Function

Sub Command1_Click()
    Dim SearchPath As String, FindStr As String
    Dim FileSize As Long
    Dim NumFiles As Integer, NumDirs As Integer
    SearchPath = "c:\"
    Open "c:\input.txt" For Input As #1
    Do While Not EOF(1)
        Line Input #1, FindStr
        Screen.MousePointer = vbHourglass
        FileSize = FindFilesAPI(SearchPath, FindStr, NumFiles, NumDirs)
        If NumFiles > 0 Then
            MsgBox "WARNING: " & NumFiles & " file(s) with name " & FindStr & " found in " & NumDirs + 1 & " Directories", vbCritical
        End If
        Screen.MousePointer = vbDefault
    Close #1
End Sub

Thanks & Cheers

Expert Comment

ID: 9640277
This will be helpful for u

Dim objFSO As Scripting.FileSystemObject
Dim  txtStream as TextStream
Dim strFileName as String
Dim File As Scripting.TextStream

Set File = objFSO.GetFile("C:\FileNames.txt")
Set txtStream = File.OpenAsTextStream(OpenFileForReading)

'Reading file names from text file
Do While Not txtStream.AtEndOfStream
      strFileName = txtStream.ReadLine
'Check whether text file is empty
      If Trim(strFileName) = "" Then
            MsgBox "No File Names found in file...!", vbInformation, "Search files"
            Exit Sub
            'Search for harmful files
            strFileName = Dir("C:\" + strFileName)
             'If found display the warning
             If Trim(strFileName) = "" Then
                    MsgBox "Harmful file  " + strFileName + "Found...!", vbInformation, "Warning"
             End If
      End If


Here I am reading file name from text file called FileName.txt and search those files in the specified path.If file found display the message.


Expert Comment

ID: 9640554
hello harryv
This   simple api function can help you a lot

Private Declare Function SearchTreeForFile Lib "imagehlp" (ByVal RootPath As String, ByVal InputPathName As String, ByVal OutputPathBuffer As String) As Long
Private Const MAX_PATH = 260
Private Sub Form_Load()
    Dim tempStr As String, Ret As Long
    Dim MyValue  As Variant
    tempStr = String(MAX_PATH, 0)
    ' you can specify the path as c:\ or d:\
    'for eg.  C:\;abc.txt
    MyValue = InputBox("Dirve and file name separted by ;")
    MyValue = Split(MyValue, ";")
    Ret = SearchTreeForFile(MyValue(0), MyValue(1), tempStr)
    If Ret <> 0 Then
        MsgBox "Located file at " + Left$(tempStr, InStr(1, tempStr, Chr$(0)) - 1)
        MsgBox "File not found!"
    End If
End Sub

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

When trying to find the cause of a problem in VBA or VB6 it's often valuable to know what procedures were executed prior to the error. You can use the Call Stack for that but it is often inadequate because it may show procedures you aren't intereste…
You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now