Jump to content

FileExists. how do i search a specific folder with an input variable for the search?


Recommended Posts

Hi guys, quick question for you.

Im making a gui that gives me a text box to type in, and a button to search for the text entered into the box.

If FileExists(GUICtrlRead($Input1)) Then

MsgBox(0, "Success", "File exists")

Else

MsgBox(4096, "Error", "Does not Exist")

EndIf

At the moment, it only searches the directory that the program is in. How can i add it to search a specific directory, or even a hard drive.

Also, is there anyway to add say .txt to the end of it, so i dont have to type findthisfile.txt, i can just type findthisfile and click search.

Its for a work project, and we have thousands of files in a directory, and we want to check if certain files are already there.

I know i can use windows search, but im trying to implement this into another project etc.

any help would be great!

Edited by royalmarine
Link to comment
Share on other sites

so i made a c:\test.txt

when i type c:\test in this input i get "file exists"

-your guictrlread was returning the state not the string -- if not the case please tell why mine kept returning 0

$Input1 = InputBox("Question", "Which file")

If FileExists($Input1 & ".txt") Then
MsgBox(0, "Success", "File exists")
Else
MsgBox(4096, "Error", "Does not Exist")
EndIf
Edited by iamtheky

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

You concatenate strings with ampersand "&".

MsgBox(0, "", "\SomeFolder\" & GUICtrlRead($Input1) & ".txt")

See Operators in the helpfile.

ok, this one worked perfectly for me.

If FileExists(GUICtrlRead($Input1) & ".txt") Then

MsgBox(0, "Success", "File exists")

Else

MsgBox(4096, "Error", "Does not Exist")

EndIf

but i still dont understand where i can put in the folder to search?

Link to comment
Share on other sites

in the input box

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

To search multiple folders and subfolders, you could employ one of the many versions of a recursive FileListToArray() that are floating around, like this 40-line version from thread 96952.

Something like:

#include <Array.au3>

GUICreate("", 300, 100)
GUICtrlCreateLabel("Filename:", 20, 20, 60, 16)
$input_filename = GUICtrlCreateInput("", 80, 20, 160, 16)
$result_message = GUICtrlCreateLabel("", 80, 50, 160, 16)
GUISetState(@SW_SHOW)

While 1
    $msg = GUIGetMsg()
    Switch $msg
        Case $input_filename
            $filename = GUICtrlRead($input_filename)
            GUICtrlSetData($result_message, "Searching...")
            $filearray = _FileListToArray_Recursive(@DesktopDir, $filename & ".txt", 1, 2, True)
            If @error Then
                GUICtrlSetData($result_message, "No matching file(s) found.")
            Else
                GUICtrlSetData($result_message, $filearray[0] & " matching file(s) found.")
;               _ArrayDisplay($filearray)
            EndIf
        Case -3
            ExitLoop
    EndSwitch
WEnd
Exit

;===============================================================================
; $iRetItemType: 0 = Files and folders, 1 = Files only, 2 = Folders only
; $iRetPathType: 0 = Filename only, 1 = Path relative to $sPath, 2 = Full path/filename
Func _FileListToArray_Recursive($sPath, $sFilter= "*", $iRetItemType = 0, $iRetPathType = 0, $bRecursive = False)
    Local $sRet = "", $sRetPath = ""
    $sPath = StringRegExpReplace($sPath, "[\\/]+\z", "")
    If Not FileExists($sPath) Then Return SetError(1, 1, "")
    If StringRegExp($sFilter, "[\\/ :> <\|]|(?s)\A\s*\z") Then Return SetError(2, 2, "")
    $sPath &= "\|"
    $sOrigPathLen = StringLen($sPath) - 1
    While $sPath
        $sCurrPathLen = StringInStr($sPath, "|") - 1
        $sCurrPath = StringLeft($sPath, $sCurrPathLen)
        $search = FileFindFirstFile($sCurrPath & $sFilter)
        If @error Then
            $sPath = StringTrimLeft($sPath, $sCurrPathLen + 1)
            ContinueLoop
        EndIf
        Switch $iRetPathType
            Case 1 ; relative path
                $sRetPath = StringTrimLeft($sCurrPath, $sOrigPathLen)
            Case 2 ; full path
                $sRetPath = $sCurrPath
        EndSwitch
        While 1
            $file = FileFindNextFile($search)
            If @error Then ExitLoop
            If ($iRetItemType + @extended = 2) Then ContinueLoop
            $sRet &= $sRetPath & $file & "|"
        WEnd
        FileClose($search)
        If $bRecursive Then
            $hSearch = FileFindFirstFile($sCurrPath & "*")
            While 1
                $file = FileFindNextFile($hSearch)
                If @error Then ExitLoop
                If @extended Then $sPath &= $sCurrPath & $file & "\|"
            WEnd
            FileClose($hSearch)
        EndIf
        $sPath = StringTrimLeft($sPath, $sCurrPathLen + 1)
    WEnd
    If Not $sRet Then Return SetError(4, 4, "")
    Return StringSplit(StringTrimRight($sRet, 1), "|")
EndFunc

Edit: added some parameter comments to function

Edited by Spiff59
Link to comment
Share on other sites

Hello Spiff59.

Would you be willing to discuss your script with me.

I like it's function, but I have a few questions and would like some help to modify this to run in a larger script I'm creating.

I know it's been two months since you posted this, but I hope you're still around. ;)

Thank you.

Edited by coffeeturtle
Link to comment
Share on other sites

Hello Spiff59.

Would you be willing to discuss your script with me.

I like it's function, but I have a few questions and would like some help to modify this to run in a larger script I'm creating.

I know it's been two months since you posted this, but I hope you're still around. ;)

Thank you.

Sure, what's the question?
Link to comment
Share on other sites

  • 2 weeks later...

There are versions in that same thread that do that as well, such as this example:

#include <Array.au3>

$array = _FileListToArray_Recursive(@DesktopDir, "", "*.txt;*.au3", "", 0, 0, True)
_ArrayDisplay($array)

; #FUNCTION# ===========================================================================================
; Name:             _FileListToArray_Recursive
; Description:      Lists files and\or folders in specified path(s)
; Syntax:           _FileListToArray_Recursive([$sPath, [$sExcludeFolderList, $sIncludeList, $sExcludeList, $iReturnType, $iReturnFormet, $bRecursive]
; Parameter(s):     $sPath = Base path of search (Required)
;                   $sExcludeFolderList = List of folders to exclude from search, semicolon delimited. Wildcards allowed. (Default = "")
;                   $sIncludeList = List of files to include in search, semicolon delimited. Wildcards allowed. (Default = "*")
;                   $sExcludeList = List of files to exclude from search, semicolon delimited. Wildcards allowed. (Default = "")
;                   $iReturnType = Include in search: 0 = Files and Folder, 1 = Files Only, 2 = Folders Only (Default = 0)
;                   $iReturnFormat = Returned element format: 0 = file/folder name only, 1 = relative path, 2 = full path (Default = 0)
;                   $bRecursive = Recursively search subfolders (Default = False)
; Return Value(s):  On success: A 0-based array containing matching folders/files
; Author(s):        Half the AutoIt Community (Thread 96952)
; ====================================================================================================
Func _FileListToArray_Recursive($sPath, $sExcludeFolderList = "", $sIncludeList = "*", $sExcludeList = "", $iReturnType = 0, $iReturnFormat = 0, $bRecursive = False)
    Local $sRet = "", $sReturnFormat = ""

    ; Edit include path (strip trailing slashes, and append single slash)
    $sPath = StringRegExpReplace($sPath, "[\\/]+\z", "") & "\"
    If Not FileExists($sPath) Then Return SetError(1, 1, "")

    ; Edit exclude folders list
    If $sExcludeFolderList Then
        ; Strip leading/trailing spaces and semi-colons, any adjacent semi-colons, and spaces surrounding semi-colons
        $sExcludeFolderList = StringRegExpReplace(StringRegExpReplace($sExcludeFolderList, "(\s*;\s*)+", ";"), "\A;|;\z", "")
        ; Convert to Regular Expression, step 1: Wrap brackets around . and $ (what other characters needed?)
        $sExcludeFolderList = StringRegExpReplace($sExcludeFolderList, '[.$]', '\[\0\]')
        ; Convert to Regular Expression, step 2: Convert '?' to '.', and '*' to '.*?'
        $sExcludeFolderList = StringReplace(StringReplace($sExcludeFolderList, "?", "."), "*", ".*?")
        ; Convert to Regular Expression, step 3; case-insensitive, convert ';' to '|', match from first char, terminate strings
        $sExcludeFolderList = "(?i)\A(?!" & StringReplace($sExcludeFolderList, ";", "$|")  & "$)"
    EndIf

    ; Edit include files list
    If $sIncludeList ="*" Then
        $sIncludeList = ""
    Else
        If StringRegExp($sIncludeList, "[\\/ :> <\|]|(?s)\A\s*\z") Then Return SetError(2, 2, "")
        ; Strip leading/trailing spaces and semi-colons, any adjacent semi-colons, and spaces surrounding semi-colons
        $sIncludeList = StringRegExpReplace(StringRegExpReplace($sIncludeList, "(\s*;\s*)+", ";"), "\A;|;\z", "")
        ; Convert to Regular Expression, step 1: Wrap brackets around . and $ (what other characters needed?)
        $sIncludeList = StringRegExpReplace($sIncludeList, '[.$]', '\[\0\]')
        ; Convert to Regular Expression, step 2: Convert '?' to '.', and '*' to '.*?'
        $sIncludeList = StringReplace(StringReplace($sIncludeList, "?", "."), "*", ".*?")
        ; Convert to Regular Expression, step 3; case-insensitive, convert ';' to '|', match from first char, terminate strings
        $sIncludeList = "(?i)\A(" & StringReplace($sIncludeList, ";", "$|")  & "$)"
    EndIf

    ; Edit exclude files list
    If $sExcludeList Then
        ; Strip leading/trailing spaces and semi-colons, any adjacent semi-colons, and spaces surrounding semi-colons
        $sExcludeList = StringRegExpReplace(StringRegExpReplace($sExcludeList, "(\s*;\s*)+", ";"), "\A;|;\z", "")
        ; Convert to Regular Expression, step 1: Wrap brackets around . and $ (what other characters needed?)
        $sExcludeList = StringRegExpReplace($sExcludeList, '[.$]', '\[\0\]')
        ; Convert to Regular Expression, step 2: Convert '?' to '.', and '*' to '.*?'
        $sExcludeList = StringReplace(StringReplace($sExcludeList, "?", "."), "*", ".*?")
        ; Convert to Regular Expression, step 3; case-insensitive, convert ';' to '|', match from first char, terminate strings
        $sExcludeList = "(?i)\A(?!" & StringReplace($sExcludeList, ";", "$|")  & "$)"
    EndIf

;   MsgBox(1,"Masks","File include: " & $sIncludeList & @CRLF & "File exclude: " & $ExcludeList & @CRLF _
;           & "Dir include : " & $FolderInclude & @CRLF & "Dir exclude : " & $ExcludeFolderList)

    If Not ($iReturnType = 0 Or $iReturnType = 1 Or $iReturnType = 2) Then Return SetError(3, 3, "")

    Local $sOrigPathLen = StringLen($sPath), $aQueue[64] = [1,$sPath], $iQMax = 63
    While $aQueue[0]
        $WorkFolder = $aQueue[$aQueue[0]]
        $aQueue[0] -= 1
        $search = FileFindFirstFile($WorkFolder & "*")
        If @error Then ContinueLoop
        Switch $iReturnFormat
            Case 1 ; relative path
                $sReturnFormat = StringTrimLeft($WorkFolder, $sOrigPathLen)
            Case 2 ; full path
                $sReturnFormat = $WorkFolder
        EndSwitch
        While 1
            $file = FileFindNextFile($search)
            If @error Then ExitLoop
            If @extended Then ; Folder
                If $sExcludeFolderList And Not StringRegExp($file, $sExcludeFolderList) Then ContinueLoop
                If $bRecursive Then
                    If $aQueue[0] = $iQMax Then
                        $iQMax += 128
                        ReDim $aQueue[$iQMax + 1]
                    EndIf
                    $aQueue[0] += 1
                    $aQueue[$aQueue[0]] = $WorkFolder & $file & "\"
                EndIf
                If $iReturnType = 1 Then ContinueLoop
            Else ; File
                If $iReturnType = 2 Then ContinueLoop
            EndIf
            If $sIncludeList And Not StringRegExp($file, $sIncludeList) Then ContinueLoop
            If $sExcludeList And Not StringRegExp($file, $sExcludeList) Then ContinueLoop
            $sRet &= $sReturnFormat & $file & "|"
        WEnd
        FileClose($search)
    WEnd
    If Not $sRet Then Return SetError(4, 4, "")
    Return StringSplit(StringTrimRight($sRet, 1), "|")
EndFunc

The function has gone from 40 to 70 lines (not counting comments) but it has a few more parameters, including the capability you ask about.

Link to comment
Share on other sites

There are versions in that same thread that do that as well, such as this example:

The function has gone from 40 to 70 lines (not counting comments) but it has a few more parameters, including the capability you ask about.

Thank you so much for finding and sharing that! I really appreciate it.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...