idoru Posted August 24, 2009 Share Posted August 24, 2009 (edited) Hi guys, I need to build a function that will search c drive for a certain file and delete all instances of it. This is all I have so far mostly from the help file. FileChangeDir("C:\") $search = FileFindFirstFile("whatever.ini") If $search = -1 Then MsgBox(0, "Error", "No files/directories matched the search pattern") EndIf While 1 $file = FileFindNextFile($search) If @error Then ExitLoop FileDelete($file) WEnd ; Close the search handle FileClose($search) I was hoping the FileChangeDir command would make it searh the entire drive rather than just the folder the script is running in but it seems not. Any ideas Thanks in advance. Edited August 24, 2009 by idoru Link to comment Share on other sites More sharing options...
Moderators Melba23 Posted August 24, 2009 Moderators Share Posted August 24, 2009 (edited) idoru,You need a recursive file search algoritm. There are several out there if you search - or you could use this one as a start and modify it to meet your needs:expandcollapse popup#include-once ; #FUNCTION# ==================================================================================================================== ; Name...........: _RecFileFinder ; Description ...: Finds files in a specified path with optional recursion. ; Syntax.........: _RecFileFinder($sPath[, $sInclude_List = "*"[, $sExclude_List = ""[, $fRecur = 0]]]) ; Parameters ....: $sPath - Initial path ; $sInclude_List - Optional: the filter for included results (default is "*"). Multiple filters must be separated by ";" ; $sExclude_List - Optional: the filter for excluded results (default is ""). Multiple filters must be separated by ";" ; $fRecur - Optional: specifies whether to search in subfolders ; |$fRecur=0 (Default) Do not search in subfolders ; |$fRecur=1 Search in subfolders ; Requirement(s).: v3.3.1.1 or higher ; Return values .: Success: 1 ; Failure: 0 and @error = 1 with @extended set as follows: ; |1 = Path not found or invalid ; |2 = Invalid $sInclude_List ; |3 = Invalid $sExclude_List ; |4 = Invalid $fRecur ; Author ........: Melba23 using SRE code from forums ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; Yes ; =============================================================================================================================== Func _RecFileFinder($sPath, $sInclude_List = "*", $sExclude_List = "", $fRecur = 0) Local $asFolderList[3] = [1], $sInclude_List_Mask, $sExclude_List_Mask Local $sCurrentPath, $hSearch, $sReturnPath = "", $sName, $fFolder ; Check valid path If Not FileExists($sPath) Then Return SetError(1, 1, "") ; Ensure trailing \ If StringRight($sPath, 1) <> "\" Then $sPath = $sPath & "\" ; Add path to folder list $asFolderList[1] = $sPath ; Determine Filter mask for SRE check If StringRegExp($sInclude_List, "\\|/|:|\<|\>|\|") Then Return SetError(1, 2, "") ; Check for invalid characters $sInclude_List = StringReplace(StringStripWS(StringRegExpReplace($sInclude_List, "\s*;\s*", ";"), 3), ";", "|") ; Strip WS and swap :/| $sInclude_List_Mask = "(?i)^" & StringReplace(StringReplace(StringReplace($sInclude_List, ".", "\."), "*", ".*"), "?", ".") & "\z" ; Convert to SRE pattern ; Determine Exclude mask for SRE check If $sExclude_List = "" Then $sExclude_List_Mask = ":" ; Set unmatchable mask Else If StringRegExp($sExclude_List, "\\|/|:|\<|\>|\|") Then Return SetError(1, 3, "") ; Check for invalid characters $sExclude_List = StringReplace(StringStripWS(StringRegExpReplace($sExclude_List, "\s*;\s*", ";"), 3), ";", "|") ; Strip WS and swap ;/| $sExclude_List_Mask = "(?i)^" & StringReplace(StringReplace(StringReplace($sInclude_List, ".", "\."), "*", ".*"), "?", ".") & "\z" ; Convert to SRE pattern EndIf ; Verify other parameter values If Not ($fRecur = 0 Or $fRecur = 1) Then Return SetError(1, 4, "") ; Search in listed folders While $asFolderList[0] > 0 ; Set path to search $sCurrentPath = $asFolderList[$asFolderList[0]] ; Reduce folder array count $asFolderList[0] -= 1 ; Get search handle $hSearch = FileFindFirstFile($sCurrentPath & "*") ; If folder empty move to next in list If $hSearch = -1 Then ContinueLoop ; Search folder While 1 $sName = FileFindNextFile($hSearch) ; Check for end of folder If @error Then ExitLoop ; Check for subfolder - @extended set in 3.3.1.1 + $fFolder = @extended ; If recursive search, add subfolder to folder list If $fRecur And $fFolder Then ; Increase folder array count $asFolderList[0] += 1 ; Double folder array size if too small (fewer ReDim needed) If UBound($asFolderList) <= $asFolderList[0] + 1 Then ReDim $asFolderList[UBound($asFolderList) * 2] ; Add subfolder to list $asFolderList[$asFolderList[0]] = $sCurrentPath & $sName & "\" EndIf ; Check file/folder type against required return value and file/folder name against Include/Exclude masks If Not $fFolder And StringRegExp($sName, $sInclude_List_Mask) And Not StringRegExp($sName, $sExclude_List_Mask) Then ;This is where you can do what you want with the found files MsgBox(0, "Result", "Found " & $sCurrentPath & $sName) EndIf WEnd ; Close current search FileClose($hSearch) WEnd EndFunc ;==>_RecFileFinderCould I suggest using FileRecycle rather then FileDelete - at least during the testing phase. >_<M23Edit: Modified the code to better reflect OPs requirements Edited August 24, 2009 by Melba23 Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind Open spoiler to see my UDFs: Spoiler ArrayMultiColSort ---- Sort arrays on multiple columnsChooseFileFolder ---- Single and multiple selections from specified path treeview listingDate_Time_Convert -- Easily convert date/time formats, including the language usedExtMsgBox --------- A highly customisable replacement for MsgBoxGUIExtender -------- Extend and retract multiple sections within a GUIGUIFrame ---------- Subdivide GUIs into many adjustable framesGUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView itemsGUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeViewMarquee ----------- Scrolling tickertape GUIsNoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxesNotify ------------- Small notifications on the edge of the displayScrollbars ----------Automatically sized scrollbars with a single commandStringSize ---------- Automatically size controls to fit textToast -------------- Small GUIs which pop out of the notification area Link to comment Share on other sites More sharing options...
idoru Posted August 24, 2009 Author Share Posted August 24, 2009 idoru, You need a recursive file search algoritm. There are several out there if you search - or you could use this one as a start and modify it to meet your needs: expandcollapse popup#include-once ; #FUNCTION# ==================================================================================================================== ; Name...........: _RecFileFinder ; Description ...: Finds files in a specified path with optional recursion. ; Syntax.........: _RecFileFinder($sPath[, $sInclude_List = "*"[, $sExclude_List = ""[, $fRecur = 0]]]) ; Parameters ....: $sPath - Initial path ; $sInclude_List - Optional: the filter for included results (default is "*"). Multiple filters must be separated by ";" ; $sExclude_List - Optional: the filter for excluded results (default is ""). Multiple filters must be separated by ";" ; $fRecur - Optional: specifies whether to search in subfolders ; |$fRecur=0 (Default) Do not search in subfolders ; |$fRecur=1 Search in subfolders ; Requirement(s).: v3.3.1.1 or higher ; Return values .: Success: 1 ; Failure: 0 and @error = 1 with @extended set as follows: ; |1 = Path not found or invalid ; |2 = Invalid $sInclude_List ; |3 = Invalid $sExclude_List ; |4 = Invalid $fRecur ; Author ........: Melba23 using SRE code from forums ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; Yes ; =============================================================================================================================== Func _RecFileFinder($sPath, $sInclude_List = "*", $sExclude_List = "", $fRecur = 0) Local $asFolderList[3] = [1], $sInclude_List_Mask, $sExclude_List_Mask Local $sCurrentPath, $hSearch, $sReturnPath = "", $sName, $fFolder ; Check valid path If Not FileExists($sPath) Then Return SetError(1, 1, "") ; Ensure trailing \ If StringRight($sPath, 1) <> "\" Then $sPath = $sPath & "\" ; Add path to folder list $asFolderList[1] = $sPath ; Determine Filter mask for SRE check If StringRegExp($sInclude_List, "\\|/|:|\<|\>|\|") Then Return SetError(1, 2, "") ; Check for invalid characters $sInclude_List = StringReplace(StringStripWS(StringRegExpReplace($sInclude_List, "\s*;\s*", ";"), 3), ";", "|") ; Strip WS and swap :/| $sInclude_List_Mask = "(?i)^" & StringReplace(StringReplace(StringReplace($sInclude_List, ".", "\."), "*", ".*"), "?", ".") & "\z" ; Convert to SRE pattern ; Determine Exclude mask for SRE check If $sExclude_List = "" Then $sExclude_List_Mask = ":" ; Set unmatchable mask Else If StringRegExp($sExclude_List, "\\|/|:|\<|\>|\|") Then Return SetError(1, 3, "") ; Check for invalid characters $sExclude_List = StringReplace(StringStripWS(StringRegExpReplace($sExclude_List, "\s*;\s*", ";"), 3), ";", "|") ; Strip WS and swap ;/| $sExclude_List_Mask = "(?i)^" & StringReplace(StringReplace(StringReplace($sInclude_List, ".", "\."), "*", ".*"), "?", ".") & "\z" ; Convert to SRE pattern EndIf ; Verify other parameter values If Not ($fRecur = 0 Or $fRecur = 1) Then Return SetError(1, 4, "") ; Search in listed folders While $asFolderList[0] > 0 ; Set path to search $sCurrentPath = $asFolderList[$asFolderList[0]] ; Reduce folder array count $asFolderList[0] -= 1 ; Get search handle $hSearch = FileFindFirstFile($sCurrentPath & "*") ; If folder empty move to next in list If $hSearch = -1 Then ContinueLoop ; Search folder While 1 $sName = FileFindNextFile($hSearch) ; Check for end of folder If @error Then ExitLoop ; Check for subfolder - @extended set in 3.3.1.1 + $fFolder = @extended ; If recursive search, add subfolder to folder list If $fRecur And $fFolder Then ; Increase folder array count $asFolderList[0] += 1 ; Double folder array size if too small (fewer ReDim needed) If UBound($asFolderList) <= $asFolderList[0] + 1 Then ReDim $asFolderList[UBound($asFolderList) * 2] ; Add subfolder to list $asFolderList[$asFolderList[0]] = $sCurrentPath & $sName & "\" EndIf ; Check file/folder type against required return value and file/folder name against Include/Exclude masks If Not $fFolder And StringRegExp($sName, $sInclude_List_Mask) And Not StringRegExp($sName, $sExclude_List_Mask) Then ;This is where you can do what you want with the found files MsgBox(0, "Result", "Found " & $sCurrentPath & $sName) EndIf WEnd ; Close current search FileClose($hSearch) WEnd EndFunc ;==>_RecFileFinder Could I suggest using FileRecycle rather then FileDelete - at least during the testing phase. >_< M23 Edit: Modified the code to better reflect OPs requirements Hi thanks for your reply, however I dont think I'm using it right. I've called the function like so _RecFileFinder("C:\") and here ;This is where you can do what you want with the found files MsgBox(0, "Result", "Found " & $sCurrentPath & $sName) ive changed it to ;This is where you can do what you want with the found files If $sName = "myfile.ini" Then MsgBox(0, "Result", "Found " & $sCurrentPath & $sName) EndIf _ This doesnt seem to be getting any results at all though. What am I doing wrong? Thanks. Link to comment Share on other sites More sharing options...
Moderators Melba23 Posted August 24, 2009 Moderators Share Posted August 24, 2009 idoru,You need to read the header information for the function! It tells you that unless you want the very basic functionality, you need to define the initial path, the files to find, any files to exclude, and whether you want it to be recursive. Your current syntax is asking the function to find all files on the C:\ root with no recursion - hardly surprising that when you then ask if there are any .ini files it comes up blank!I see you want to find all .ini files on the C drive, so use this (Translation: look in the C drive, look for *.ini files, exclude nothing, look in subfolders (recursive)):_RecFileFinder("C:\", "*.ini", "", 1) and remove your redundant If $sName = "myfile.ini" Then line - the function will have already done that bit for you if you ask it correctly!One final thought - are you using the Beta release? If not, then replace this line:$fFolder = @extendedwith this:$fFolder = StringInStr(FileGetAttrib($sCurrentPath & $sName), "D")The function is much slower, but does not need the new Beta.M23 Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind Open spoiler to see my UDFs: Spoiler ArrayMultiColSort ---- Sort arrays on multiple columnsChooseFileFolder ---- Single and multiple selections from specified path treeview listingDate_Time_Convert -- Easily convert date/time formats, including the language usedExtMsgBox --------- A highly customisable replacement for MsgBoxGUIExtender -------- Extend and retract multiple sections within a GUIGUIFrame ---------- Subdivide GUIs into many adjustable framesGUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView itemsGUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeViewMarquee ----------- Scrolling tickertape GUIsNoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxesNotify ------------- Small notifications on the edge of the displayScrollbars ----------Automatically sized scrollbars with a single commandStringSize ---------- Automatically size controls to fit textToast -------------- Small GUIs which pop out of the notification area Link to comment Share on other sites More sharing options...
idoru Posted August 24, 2009 Author Share Posted August 24, 2009 idoru, You need to read the header information for the function! It tells you that unless you want the very basic functionality, you need to define the initial path, the files to find, any files to exclude, and whether you want it to be recursive. Your current syntax is asking the function to find all files on the C:\ root with no recursion - hardly surprising that when you then ask if there are any .ini files it comes up blank! I see you want to find all .ini files on the C drive, so use this (Translation: look in the C drive, look for *.ini files, exclude nothing, look in subfolders (recursive)): _RecFileFinder("C:\", "*.ini", "", 1) and remove your redundant If $sName = "myfile.ini" Then line - the function will have already done that bit for you if you ask it correctly! One final thought - are you using the Beta release? If not, then replace this line: $fFolder = @extended with this: $fFolder = StringInStr(FileGetAttrib($sCurrentPath & $sName), "D") The function is much slower, but does not need the new Beta. M23 I had originally tried this syntax to no avail. I'm not using the beta release either which I suppose must have been the problem or at least part of it. Thanks very much for your help its greatly appreciated. Link to comment Share on other sites More sharing options...
Moderators Melba23 Posted August 24, 2009 Moderators Share Posted August 24, 2009 idoru,Glad I could help! M23P.S. If you use the "Add Reply" button at the top and bottom of each page rather than the "Reply" button in the post itself, you do not repeat the contents of the previous post in yours. It makes for a more compact topic and you can imagine the result if everyone repeated everything over a long discussion..... >_< Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind Open spoiler to see my UDFs: Spoiler ArrayMultiColSort ---- Sort arrays on multiple columnsChooseFileFolder ---- Single and multiple selections from specified path treeview listingDate_Time_Convert -- Easily convert date/time formats, including the language usedExtMsgBox --------- A highly customisable replacement for MsgBoxGUIExtender -------- Extend and retract multiple sections within a GUIGUIFrame ---------- Subdivide GUIs into many adjustable framesGUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView itemsGUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeViewMarquee ----------- Scrolling tickertape GUIsNoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxesNotify ------------- Small notifications on the edge of the displayScrollbars ----------Automatically sized scrollbars with a single commandStringSize ---------- Automatically size controls to fit textToast -------------- Small GUIs which pop out of the notification area Link to comment Share on other sites More sharing options...
idoru Posted August 24, 2009 Author Share Posted August 24, 2009 noted >_ Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now